Files
Sam Kumar 21105b5e05 feat/Resource monitor/CU 86b7mzbtx (#33)
* docs(AGENTS.md): add guidance on using Chrome DevTools MCP tool for UI changes to improve development process and ensure accuracy in modifications

* feat(docs): add Resource Monitor documentation and initial implementation details for the restart button feature
docs(docs): update README.md to include Resource Monitor link and overview

feat(resource_monitor.js): add resource monitor extension with restart button to ComfyUI top bar

This extension enhances the user interface by integrating a resource
monitor similar to Crystools, allowing for future CPU/RAM/GPU/VRAM
monitoring capabilities.

* feat: remove restart button extension and associated styles from Swiss Army Knife

* feat(resource_monitor.js): implement restart functionality for ComfyUI server with user notification and error handling

* fix(resource_monitor.js): change reload timeout from 2 seconds to 5 seconds to allow more time for reconnection
feat(resource_monitor.js): use hard reload to bypass cache when reloading the page for better resource updates

* feat(monitor): add resource monitor service and API endpoints for hardware monitoring
feat(monitor): initialize resource monitor service in __init__.py and register API routes
chore(monitor): create utility modules for hardware and GPU information handling

feat(gpu_info.py): add GPU information collector to monitor VRAM, utilization, and temperature

This new module collects GPU metrics using pynvml and torch, providing detailed information about available GPUs and their performance. It enhances monitoring capabilities for applications utilizing GPU resources.

feat(monitoring): add hardware information collector and monitoring service to gather and broadcast system metrics

- Introduce `hardware_info.py` to collect CPU, RAM, and disk usage metrics.
- Implement `monitor_service.py` to periodically collect and broadcast hardware metrics.
- Update `requirements.txt` to include necessary dependencies: psutil, pynvml, and py-cpuinfo.

feat(tests): add test script for resource monitor backend to verify hardware monitoring functionality

* docs(Resource Monitor Testing): add comprehensive testing guide for resource monitor implementation to ensure proper functionality and user experience

feat(resource_monitor.js): enhance resource monitoring with dynamic display and color coding for CPU, RAM, and GPU metrics

- Add styles for resource monitor display and labels.
- Create functions to format and update monitor values.
- Implement dynamic creation of monitor elements based on available hardware.
- Fetch initial status and listen for updates via WebSocket to keep metrics current.

* refactor(resource_monitor.js): move restart button to be added after monitors for better UI flow

* feat(resource_monitor.js): enhance server restart process with health checks and user feedback
style(resource_monitor.js): improve button styles and layout for better UX
refactor(resource_monitor.js): extract GPU model name for clearer display in UI
fix(resource_monitor.js): update formatting for memory and CPU display values

* feat(resource_monitor): update UI to a floating HUD with live telemetry and inline restart workflow

* docs(RESOURCE_MONITOR): update roadmap section with near-term enhancements and ProfilerX parity plan

* style(resource_monitor.js): enhance restart button styles for improved UI aesthetics and usability

* style(resource_monitor.js): update font size and line height for better readability in the restart button styles

* style(resource_monitor.js): update CSS styles for swissarmyknife-monitor class to enhance layout and readability

* docs(RESOURCE_MONITOR.md): update the ProfilerX Parity Plan section to include detailed implementation hooks and phases for better clarity and guidance
style(resource_monitor.js): improve CSS styles for monitor content and labels to enhance readability and layout consistency

* feat(resource_monitor.js): add background progress bar to monitor display for better visual feedback
refactor(resource_monitor.js): update percentage thresholds for color changes in progress bar for improved clarity

* style(resource_monitor.js): adjust divider styles for better alignment and visibility in resource monitor UI

* style(resource_monitor.js): update styles for the restart button to enhance appearance and usability

* style(resource_monitor.js): update styles for restart button to use flexbox for better alignment
refactor(resource_monitor.js): simplify GPU and VRAM display labels for consistency and clarity

* style(resource_monitor.js): update button styles to center content and adjust padding for better layout

* style(resource_monitor.js): update restart button class for consistent styling

* feat(profiler): implement profiling hooks and API for workflow performance tracking

* feat(profiler): add workflow profiling functionality with UI integration

- Implemented NodeProfile and WorkflowProfile classes for tracking execution time, VRAM/RAM usage, and cache hits.
- Created ProfilerManager as a singleton to manage profiling sessions and history.
- Added methods for starting and ending workflows and nodes, including VRAM and RAM tracking.
- Introduced a new button in the resource monitor UI to access the profiler.
- Developed a popup interface to display profiling statistics and node performance.
- Implemented fetching and displaying of profiler data with retry logic.
- Styled the profiler UI components for better user experience.
- Added functionality to clear profiler history and view full history in a modal.

* feat(prompt_builder): add Prompt Builder node for custom prompt composition
feat(resource_monitor): enhance resource monitor UI with action button group and improved button styles

* feat(profiler): enhance workflow profiling with console logging and data fetching improvements

* feat(profiler): add execution time logging for node profiling and adjust popup positioning

* feat(prompt_builder): add Prompt Builder node documentation and quick reference guide
feat(media_describe): update override fields for backward compatibility and clarity

* feat(media_describe): rename 'override_movement' to 'override_action' for consistency

* feat(prompt_builder): update MediaDescribeOverrides documentation and add Prompt Builder node details

* feat(prompt_builder): import Prompt Builder node and update mappings

* feat(profiler): enhance profiling with VRAM tracking and execution timing for nodes

* feat(prompt_builder): update Prompt Builder node to streamline input parameters and enhance documentation

* feat(lora_info_extractor): add LoRA Info Extractor node for enriched metadata extraction and CivitAI lookup

* feat(lora_info_extractor): integrate LoRA Info Extractor node and update documentation

* refactor(civit_metadata_helper.py): improve code readability and structure by reformatting input types and updating docstrings

feat(civit_metadata_helper.py): enhance metadata collection with structured outputs for better CivitAI submissions

refactor(civit_metadata_helper.py): restructure collect_metadata method for better readability and maintainability
feat(civit_metadata_helper.py): add type hints to method signatures for improved clarity and type safety
chore(civit_metadata_helper.py): clean up code by removing commented-out sections and improving prompt handling

* feat(civit_metadata_helper): add input normalization for metadata collection to handle various data types

* feat(config_api.py): add profiler_enabled setting to configuration for enhanced performance tracking
feat(prestartup.py): integrate profiler_enabled check to conditionally enable profiling functionality
feat(swiss-army-knife.js): add UI option for enabling/disabling workflow profiler and sync with backend settings

* feat(resource_monitor.js): enhance hard reload functionality with multiple methods for better browser compatibility
style(resource_monitor.js): adjust popup positioning and styles for improved layout and user experience
style(resource_monitor.js): update action button group to a vertical layout for better accessibility

* feat(resource_monitor.js): refactor style injection to load external CSS for resource monitor and update monitor display logic

* feat(resource_monitor): enhance documentation with known limitations and troubleshooting tips for profiling features

* feat(profiler): add GPU model tracking and tooltip display for loaded models

* feat(resource_monitor): add execution glow effect to monitor during workflow execution

* feat(resource_monitor): enhance workflow execution glow effect with dual pseudo-elements for improved visual feedback

* feat(resource_monitor): enhance duration formatting for total execution time in profiler stats

* feat(resource_monitor): enhance monitor layout with inner wrapper for improved telemetry display

* feat: Implement GPU memory scanning and enhanced model detection

- Added direct GPU memory scanning in `profiler_core.py` to track loaded models using Python's garbage collector.
- Removed fragile node-name tracking and implemented a caching mechanism for model scans.
- Introduced comprehensive debug logging in `resource_monitor.js` for better troubleshooting.
- Enhanced model grouping by extracting metadata from safetensors files, allowing for user-friendly model names and accurate VRAM reporting.
- Implemented a five-phase approach to identify top-level models, calculate VRAM, and match with metadata.
- Improved performance with caching strategies and optimized scanning logic to limit results to top 10 models per GPU.
- Added tests and validation steps to ensure accurate model detection and reporting.

* feat(resource_monitor): enhance logging with color-coded messages and improve VRAM tooltip functionality

* feat(resource_monitor): implement OOM diagnosis and prevention features with enhanced logging and tooltip updates

* feat(prestartup.py): implement OOM detection and logging for PyTorch errors to enhance error handling and debugging capabilities

feat(profiler_core.py): add out-of-memory (OOM) detection and tracking fields to NodeProfile and WorkflowProfile for better resource management
feat(profiler_core.py): implement OOM statistics update logic in ProfilerManager to track OOM occurrences and their details
fix(profiler_core.py): ensure VRAM usage is monitored before node execution to prevent OOM issues

feat(profiler_core.py): add OOM statistics and analytics to ProfilerManager for better monitoring and recommendations
fix(profiler_core.py): include OOM summary in archived workflows to enhance data insights

* fix(profiler_core.py): update OOM event to calculate execution time from start and end times for better performance tracking

* feat(resource_monitor): add OOM analysis UI with detailed statistics and recommendations

* feat(resource_monitor): implement comprehensive OOM detection and analysis features with frontend UI enhancements

* feat(profiler): enhance profiler popup interaction with hover and timeout logic

* fix(prompt_builder.py): change join delimiter from single newline to double newline for better prompt formatting

* feat(docs): add detailed character analysis system prompt to structured output documentation for clarity and usage guidance
feat(llm_studio_structured.py): update system prompt to reflect character analysis focus and improve output consistency
docs(LLMStudioStructuredDescribe.md): create new documentation file for structured description node with usage tips and input/output details

* feat(docs): add comprehensive guidelines for custom node documentation using Markdown

* refactor: Remove retired Media Describe, LLM Studio Describe Nodes

* refactor: rename docs to dev-docs

* docs: update developer documentation for clarity and structure

* refactor: remove filename generator, update video metadata, show text and control panel overview nodes

* feat: add NSFW field to schemas and prompts for structured output nodes

* ♻️ (llm_studio_structured.py): refactor nsfw field type from boolean to string for better clarity and flexibility in handling NSFW content descriptions.

* ♻️ (llm_studio_structured.py): refactor max_tokens configuration to increase max limit and change step size for better granularity in token generation settings

* ✨ (prompt_builder.py): add support for NSFW text override in PromptBuilder to enhance prompt customization options

* feat(media-selection): enhance media source options to include Redgifs and Gfycat URLs for better media retrieval
fix(media-selection): update error messages to reflect new media source options for clarity
fix(llm_studio_structured.py): increase max_tokens default value to accommodate larger inputs
test(redgifs): add unit tests for downloading media from Redgifs to ensure functionality and error handling

test: add tests for direct download functionality from Redgifs to ensure reliability and correctness of media selection
docs: update MediaSelection documentation to include support for direct Redgifs URLs in media sourcing options

* feat: add script to fix ComfyUI base64 payloads by locating JPEG start and writing preview

* feat(nodes): add ParseStringToBBox node to parse JSON-style bbox strings into float coordinates
feat(nodes): update NODE_CLASS_MAPPINGS and NODE_DISPLAY_NAME_MAPPINGS to include ParseStringToBBox
test: add unit tests for ParseStringToBBox to validate correct parsing and error handling

* feat(parse_string_to_bbox): update bbox parsing to return integer coordinates and dimensions for better usability
test(parse_string_to_bbox): update tests to validate new integer output format and add new test for rounding behavior
test(parse_string_to_bbox_ints): add new tests for parsing bbox strings to integer coordinates and validate error handling

* feat(docs): add detailed documentation for ParseStringToBBox node including inputs, outputs, and usage tips

* ✨ (llm_studio_structured.py): introduce new structured description features for subject appearance and video frames
📝 (llm_studio_structured.py): update documentation for new input types and prompts
♻️ (llm_studio_structured.py): refactor node registration to include new combined structured describe class

* ✨ (llm_studio_structured.py): introduce new SUBJECT_APPEARANCE_SCHEMA and VIDEO_FRAME_ARCHITECT_SCHEMA to enhance media description capabilities with detailed attributes for subject appearance and video frame analysis.

* ✨ (media_describe): add LMStudioCombinedStructuredDescribe to exports for enhanced functionality
✨ (nodes): include LMStudioCombinedStructuredDescribe in mappings for improved node support

* 📝 (llm_studio_structured.py): update prompts for clarity and detail to enhance user guidance and output structure
♻️ (llm_studio_structured.py): refactor combined text generation to improve readability and maintainability by using list comprehension

* ✨ (llm_studio_structured.py): update schema presets and default values to enhance functionality
♻️ (llm_studio_structured.py): refactor frame extraction to return metadata instead of paths for better data handling
💡 (llm_studio_structured.py): improve content building logic to allow custom content for structured output
📝 (llm_studio_structured.py): update comments for clarity and maintainability of the code

* ✨ (llm_studio_structured.py): add 'subject' field to VIDEO_FRAME_ARCHITECT_SCHEMA for better video description
♻️ (llm_studio_structured.py): update required fields in schema to include 'subject' and 'summary' for improved validation
♻️ (llm_studio_structured.py): refactor conditionals to handle new schema preset 'video_frame_architect' for enhanced functionality

* ♻️ (llm_studio_structured.py): remove subject field from VIDEO_FRAME_ARCHITECT_SCHEMA to simplify schema requirements
♻️ (llm_studio_structured.py): update field assignments in LLMStudioStructuredDescribe to reflect schema changes

* ✨ (llm_studio_structured.py): enhance NSFW summary handling by adding support for structured notes and summaries to improve content description clarity

* ✨ (llm_studio_structured.py): add formatted_response to return types and names for improved output structure
♻️ (llm_studio_structured.py): refactor NSFW handling to separate plain and formatted responses for better clarity
💡 (llm_studio_structured.py): enhance response formatting for better readability and organization of output sections

* ✨ (llm_studio_structured.py): add minItems and maxItems constraints to frames array to enforce validation rules on video frame data

* 📝 (llm_studio_structured.py): add 'subject' property to VIDEO_FRAME_ARCHITECT_SCHEMA for better metadata representation
📝 (llm_studio_structured.py): update descriptions for NSFW analysis and frame metadata for clarity
📝 (llm_studio_structured.py): modify required fields in schema to include 'subject' and adjust 'has_nsfw' to 'summary'

* ✨ (llm_studio_structured.py): add 'timestamp_seconds' and 'frames' to required fields to ensure necessary data is provided for video frame descriptions

* ♻️ (llm_studio_structured.py): refactor frame index calculation to improve handling of invalid fps and ensure proper frame extraction
✨ (llm_studio_structured.py): add fallback for fps and enhance frame index tracking for better frame management

* 💡 (llm_studio_structured.py): add debug logging for frame indices and file details to assist in troubleshooting
🐛 (llm_studio_structured.py): improve verbose logging for base64 encoding to catch potential issues with short encodings

* ✨ (azure_queue_publisher.py, .env.example, config_api.py, nodes.py, swiss-army-knife.js): introduce Azure Queue Publisher node to publish job events to Azure Storage Queue for event-driven architecture
📝 (requirements.txt): add azure-storage-queue dependency to support Azure Queue operations
🔧 (config_api.py): update config API to include Azure job events queue in settings
💡 (swiss-army-knife.js): add function to retrieve Azure job events queue from settings for better integration
♻️ (various files): refactor code for improved readability and maintainability, including consistent formatting and logging updates

* ✨ (routes): add event routes for emitting events and health check to enhance API functionality
🐛 (azure_queue_publisher.py): add prompt_id as an optional parameter to improve event data structure
♻️ (azure_queue_publisher.py): change character_index condition to allow zero value for better logic
📝 (init.py): register new event routes in the application to ensure proper routing

* ✨ (events.py): enhance event route registration to prefer PromptServer API
🐛 (events.py): add fallback to aiohttp router and improve error handling
💡 (events.py): add diagnostics logging for registered routes in debug mode

* ✨ (events.py): enhance event route registration with best-effort fallbacks
to improve reliability and diagnostics in case of registration failures

* ✨ (routes/events.py): refactor event route registration to use ComfyUI's
recommended pattern for better maintainability and clarity
📝 (init.py): update event route registration to auto-import events module
for automatic route initialization and improve error handling

* ♻️ (events.py): refactor to remove os dependency and use Swiss Army Knife config system for connection string and queue name retrieval to improve maintainability and flexibility

* ✨ (execution_hooks): add execution hooks for automatic event publishing
to Azure Queue during workflow execution

📝 (init.py): import execution hooks to register them into ComfyUI
execution lifecycle and handle import exceptions gracefully

* ✨ (execution_hooks.py): refactor execution hooks to integrate with PromptServer's message bus for improved event handling
🐛 (execution_hooks.py): update event handling methods to manage prompt lifecycle and error messages more effectively
📝 (execution_hooks.py): enhance module documentation for clarity on functionality and usage

* 💡 (execution_hooks.py): add comments to clarify the behavior of execution events and their handling

* ✨ (events.py): optimize JSON serialization by using custom separators for smaller payloads
💡 (events.py): add logging for published queue payload to improve traceability

* ✨ (media_selection.py): add support for Azure Blob Storage as a media source with validation and downloading functionality

* ✨ (docs, config_api, media_describe): add support for configurable LM Studio base URL to enhance flexibility and usability
📝 (docs): update documentation to reflect changes in base_url input and its usage
♻️ (config_api, media_describe): refactor code to resolve LM Studio base URL from settings or environment variables for better maintainability

* 📝 (STRUCTURED_OUTPUT_IMPLEMENTATION.md): update documentation to clarify
LM Studio endpoint usage and remove base_url parameter from input
definitions for consistency

♻️ (llm_studio_structured.py): refactor code to remove base_url parameter
from describe_image and describe_video methods, relying on global
LM Studio endpoint configuration

✨ (swiss-army-knife.js): add debug logging for model dropdown interactions
to enhance traceability and debugging capabilities in the UI

* ✨ (azure_queue_publisher.py, execution_hooks.py, events.py): add audit logging for event publishing to track success and failure
💡 (execution_hooks.py): refactor logging logic into a separate method for clarity and reuse
📝 (azure_queue_publisher.py, execution_hooks.py, events.py): improve code comments for better understanding of audit logging functionality

* ♻️ (init.py, azure_queue_publisher.py, execution_hooks.py, events.py): refactor import paths to ensure package root is discoverable for modules
💡 (init.py, azure_queue_publisher.py, execution_hooks.py, events.py): add comments to clarify the purpose of modifying sys.path for module loading

* ♻️ (init.py, azure_queue_publisher.py, execution_hooks.py, events.py): refactor import statements to use relative imports for better module organization and maintainability

* ✨ (audit_logger_loader.py): introduce a helper module to load audit_logger
🐛 (azure_queue_publisher.py, execution_hooks.py, events.py): update import paths to use the new audit_logger_loader for better module management

* ✨ (init.py): introduce dynamic loading of the lib package to handle
hyphenated module names and improve import reliability
♻️ (audit_logger_loader.py): remove redundant audit logger loader module
as its functionality is now integrated into __init__.py
🔧 (azure_queue_publisher.py, execution_hooks.py, events.py): update
imports to reference the new lib package structure for audit logger

* ✨ (audit_logger): introduce AuditLogger class for structured logging of job audit events
♻️ (imports): refactor import statements to use relative imports for consistency
📝 (gitignore): update .gitignore to exclude specific directories and files
🔧 (pyproject.toml): update package configuration to include "routes" package
📝 (init.py): remove unused code and clean up __init__.py for better readability

* ✨ (app_insights.py): add Application Insights logging and tracing support to monitor application performance and errors
♻️ (events.py): integrate Application Insights logger into event emission process for better observability of events and errors

* ♻️ (azure_queue_publisher.py, execution_hooks.py, audit_logger.py, events.py): refactor timestamp formatting to use 'Z' instead of '+00:00' for better compatibility with ISO 8601
♻️ (azure_queue_publisher.py, execution_hooks.py, audit_logger.py): refactor JSON serialization to use custom separators for more compact output

* ♻️ (execution_hooks.py, events.py): refactor queue name retrieval to use a fallback with or operator for better clarity and consistency

* ✨ (azure_queue_publisher.py, execution_hooks.py, audit_logger.py, events.py): add TextBase64EncodePolicy to QueueClient initialization for better message encoding
💡 (azure_queue_publisher.py, execution_hooks.py, audit_logger.py, events.py): update timestamp formatting to include seconds for improved precision

* ✨ (civit_metadata_helper.py): add optional JSON fields for subject and video prompts to enhance metadata collection

* ✨ (civit_metadata_helper.py): add JSON parsing for subject and video prompts to handle structured data inputs
📝 (civit_metadata_helper.py): update return structure to include parsed subject and video prompts for better data handling

* ✨ (init.py, config_api.py, upload_job_to_azure.py): introduce Upload Job to Azure node to upload files to Azure Blob Storage and create job documents in CosmosDB
♻️ (init.py): rename Azure Storage Upload node to Upload Job to Azure for clarity
📝 (upload-job-to-azure.md): add documentation for Upload Job to Azure node detailing its purpose, inputs, outputs, and configuration
🔧 (config_api.py): add configuration settings for Azure Cosmos DB connection and job container
🐛 (azure_storage_upload.py): remove obsolete Azure Storage Upload node code as it is replaced by the new Upload Job to Azure node

* ✨ (execution_hooks.py, llm_studio_structured.py, cosmos_utils.py): add functionality to push structured analysis results to CosmosDB for job tracking
📝 (execution_hooks.py): add get_current_prompt_id function to retrieve the current job ID
♻️ (llm_studio_structured.py): refactor code to utilize current job ID for metadata updates in CosmosDB
📝 (cosmos_utils.py): add utility functions for interacting with Azure CosmosDB and Blob Storage

* ♻️ (cosmos_utils.py): refactor container name from "media" to "media-files" for better clarity and organization

* ✨ (llm_studio_structured.py): update keys in cosmos_meta to use snake_case for consistency
📝 (cosmos_utils.py): replace logger.debug with print statements for better visibility of errors and status messages

* ✨ (Dockerfile, requirements.txt, swiss-army-knife.js): add Azure Cosmos DB support to enhance data storage capabilities and improve integration with Azure services.

* 💡 (cosmos_utils.py): add comments to clarify the use of 'id' as partition key
✅ (cosmos_utils.py): update replace_item method to include partition_key for consistency

* 💡 (cosmos_utils.py): update comments to clarify the use of jobId field as partition key
🐛 (cosmos_utils.py): fix partition key usage in replace_item to use jobId field value for consistency

* ✨ (cosmos_utils.py): add support for PartitionKey to handle undefined partition keys in CosmosDB
🐛 (cosmos_utils.py): improve error handling and logging for document queries and updates
💡 (cosmos_utils.py): clarify comments regarding partition key discrepancies and operations
2026-01-13 07:23:51 -06:00

13 KiB
Raw Permalink Blame History

Enhanced GPU Model Detection with Metadata Extraction

Status: ✅ Implemented
Date: November 29, 2025
Component: Resource Monitor - GPU Profiling
Related Files:

  • nodes/utils/resource_monitor/profiler_core.py (lines 1-600)
  • web/js/resource_monitor.js (tooltip display)

Problem Statement

Initial GPU model scanning detected 603 individual layer components (WanLayerNorm, WanRMSNorm, WanSelfAttention) instead of showing meaningful parent models. Users saw:

  • ❌ 603 entries showing "WanLayerNorm (model, 0.0 GB)"
  • ❌ No correlation to user-selected model filenames
  • ❌ Technical class names instead of user-friendly names
  • ❌ All layers showing 0.0 GB (incorrect sizing)

User Requirement: "The average comfyui user won't understand these levels"

Solution Overview

Enhanced three-phase approach that:

  1. Reads safetensors metadata during model loading
  2. Groups child layers under parent models
  3. Displays user-friendly names with accurate VRAM usage

Example Output

Before: 603 × WanLayerNorm (model, 0.0 GB)

After:

  • Wan2_2-T2V-A14B-HIGH (checkpoint, 2.1 GB, 145 layers)
  • VACE-Depth (model, 512 MB, 45 layers)
  • MyLoRA (lora, 128 MB, 32 layers)

Implementation Details

1. Safetensors Metadata Extraction

File: profiler_core.py (lines 1-20)

# Import safetensors library for metadata reading
try:
    from safetensors import safe_open
    SAFETENSORS_AVAILABLE = True
except ImportError:
    SAFETENSORS_AVAILABLE = False

Installation:

pip3 install safetensors

Purpose: Read model_type and other metadata directly from .safetensors files

2. Pending Model Loads Tracking

File: profiler_core.py (lines 136-141)

# Track pending model loads with metadata (filename, timestamp, metadata)
self._pending_model_loads: List[Dict[str, Any]] = []
self._pending_loads_max_age: float = 5.0  # Keep pending loads for 5 seconds

Purpose: Store model filenames and metadata during node execution for later correlation with loaded modules

3. Model Metadata Capture

File: profiler_core.py (_capture_model_metadata() method, lines 449-489)

Triggered: During start_node() before model execution

Process:

  1. Scan node inputs for file path keys: model, checkpoint, ckpt_name, lora_name, etc.
  2. Filter for .safetensors files
  3. Read metadata using safe_open()
  4. Store in _pending_model_loads with timestamp

Example:

# Input: {'ckpt_name': 'Wan2_2-T2V-A14B-HIGH_fp8.safetensors'}
# Reads metadata: {'model_type': 'Wan2_2-T2V-A14B-HIGH', ...}
# Stores: {
#     'filename': 'Wan2_2-T2V-A14B-HIGH_fp8.safetensors',
#     'timestamp': 1732901234.56,
#     'node_type': 'WanVideoModelLoader',
#     'metadata': {'model_type': 'Wan2_2-T2V-A14B-HIGH'}
# }

4. Enhanced GPU Scanning with Grouping

File: profiler_core.py (_scan_gpu_models() method, lines 270-444)

Five-Phase Process:

Phase 1: Collect All CUDA Modules

  • Scan all Python objects using gc.get_objects()
  • Filter for torch.nn.Module instances
  • Build parent/child relationship map using named_children()
  • Only count direct parameters (recurse=False)
for param in obj.parameters(recurse=False):  # Only direct params
    if param.device.type == 'cuda':
        size_bytes += param.nelement() * param.element_size()

Phase 2: Identify Top-Level Parents

  • Find modules that are NOT children of other modules
  • These represent complete models (not individual layers)
top_level_parents = set(all_cuda_modules.keys()) - set(parent_child_map.keys())

Phase 3: Calculate Total VRAM

  • For each parent, traverse all descendants using depth-first search
  • Sum VRAM across all child layers
  • Count total layers and parameters
# Depth-first traversal through module hierarchy
stack = [parent_id]
while stack:
    current_id = stack.pop()
    total_size_bytes += current_data['size_bytes']
    layer_count += 1
    stack.extend(current_data['children'])

Phase 4: Extract Model Names

  • Try module attributes: name, model_name, config._name_or_path
  • Try module metadata: __metadata__['model_type']
  • Match to _pending_model_loads by timestamp
  • Use safetensors model_type field if available
model_name = self._extract_model_name(module, model_class)
metadata = self._match_pending_metadata(size_mb, model_class)
if metadata and 'model_type' in metadata:
    model_name = metadata['model_type']

Phase 5: Format Display Names

  • Show model type, size (GB or MB), layer count
  • Sort by VRAM usage (descending)
  • Limit to top 10 models per GPU
display_name = f"{model_name} ({model_type}, {size_str}, {layer_count} layers)"
# Example: "Wan2_2-T2V-A14B-HIGH (checkpoint, 2.1 GB, 145 layers)"

5. Helper Methods

_read_safetensors_metadata(filepath: str)

Lines: 491-527

  • Resolves relative paths to common ComfyUI model directories
  • Opens safetensors file with safe_open()
  • Extracts metadata dictionary
  • Returns {'model_type': '...', ...} or None

Paths Checked:

possible_dirs = [
    Path('/workspace/ComfyUI/models/checkpoints'),
    Path('/workspace/ComfyUI/models/loras'),
    Path('/workspace/ComfyUI/models/vae'),
    Path('/workspace/ComfyUI/models/unet'),
    Path('models/checkpoints'),
    Path('models/loras'),
    # ... etc
]

_extract_model_name(module, default_name: str)

Lines: 529-552

  • Tries common attribute patterns on PyTorch module
  • Checks config._name_or_path for HuggingFace models
  • Checks __metadata__['model_type'] for safetensors
  • Falls back to class name if nothing found

_match_pending_metadata(size_mb: float, class_name: str)

Lines: 554-578

  • Matches loaded module to pending metadata by timestamp
  • Returns most recent load with metadata
  • Fallback: returns most recent load even without metadata
  • Used for correlating GPU modules to user-selected files

_classify_model_type(class_name: str)

Lines: 580-597

  • Updated with WanVideo patterns: wanvideo, wan2
  • Returns: checkpoint, lora, vae, clip, controlnet, upscaler, depth, model

Technical Challenges Solved

Challenge 1: Layer-Level Detection

Problem: Detecting 603 individual layers instead of 5-10 models

Solution: Build parent/child hierarchy and only report top-level parents

Impact: Reduced from 603 entries to ~5-10 meaningful models

Challenge 2: Zero VRAM Reporting

Problem: All layers showing 0.0 GB

Solution:

  • Only count direct parameters with recurse=False
  • Traverse children separately and sum VRAM
  • Calculate at parent level including all descendants

Impact: Accurate VRAM reporting (e.g., 2.1 GB for Wan2 model)

Challenge 3: Filename Correlation

Problem: No way to match detected modules to user-selected files

Solution:

  • Capture filenames during start_node()
  • Read safetensors metadata immediately
  • Store with timestamp for correlation
  • Match by timing when scanning GPU

Impact: Display "Wan2_2-T2V-A14B-HIGH" instead of "WanTransformerDecoder"

Challenge 4: Block Swapping / RAM Offloading

Problem: WanVideo models use block swapping - parts may be in RAM

Solution:

  • Only scan CUDA memory (param.device.type == 'cuda')
  • Automatically handles offloaded models
  • Only reports what's actually on GPU

Impact: Accurate representation of GPU state

Performance Optimizations

1. Scan Caching

Implementation: get_loaded_models() method (lines 600+)

# Cache scan results for 1 second
if self._model_scan_cache_timestamp:
    age = time.time() - self._model_scan_cache_timestamp
    if age < self._model_scan_cache_ttl:
        return self.loaded_models  # Return cached

Impact: Prevents expensive scans on every API request

2. Cache Invalidation

Implementation: end_node() method

# Invalidate if VRAM changed by more than 100MB
vram_change = abs(node_profile.vram_after - node_profile.vram_before)
if vram_change > 100 * 1024 * 1024:  # 100MB threshold
    self._model_scan_cache_timestamp = None

Impact: Fresh scans only when models actually load/unload

3. Garbage Collection

Implementation: _scan_gpu_models() line 288

# Force GC before scanning to get accurate state
gc.collect()

Impact: Ensures dead references are cleaned up before counting

4. Top 10 Limit

Implementation: Phase 5 of scanning

# Sort by VRAM and limit to top 10
result[gpu_id].sort(key=lambda x: x['vram_mb'], reverse=True)
result[gpu_id] = result[gpu_id][:10]

Impact: Prevents overwhelming UI with hundreds of models

5. Pending Loads Cleanup

Implementation: Lines 291-295

# Clean up old pending loads (>5 seconds)
self._pending_model_loads = [
    load for load in self._pending_model_loads
    if current_time - load.get('timestamp', 0) < 5.0
]

Impact: Prevents memory leak from accumulating metadata

Testing & Validation

Test Scenario 1: WanVideo Model Loading

Setup: Load Wan2_2-T2V-A14B-HIGH model with block swapping

Expected Output:

GPU 0: 5 models
  - Wan2_2-T2V-A14B-HIGH (checkpoint, 2.1 GB, 145 layers)
  - VACE-Depth (model, 512 MB, 45 layers)
  - MyLoRA (lora, 128 MB, 32 layers)

Validation:

  • ✅ Shows grouped parent model, not 603 layers
  • ✅ Accurate VRAM calculation (2.1 GB)
  • ✅ Displays user-friendly name from metadata
  • ✅ Shows layer count for context

Test Scenario 2: Multiple Model Types

Setup: Load checkpoint + VAE + LoRA + CLIP

Expected Output: 4-5 distinct models sorted by VRAM

Test Scenario 3: Model Unloading

Setup: Clear models and observe cache invalidation

Expected Output: Empty model list after VRAM drops

Test Scenario 4: Without Safetensors Library

Setup: Remove safetensors package

Expected Output: Graceful degradation, shows class names instead of metadata

Dependencies

Required

  • torch - PyTorch module inspection
  • gc - Python garbage collection

Optional

  • safetensors - Metadata extraction (highly recommended)

Installation:

pip3 install safetensors

Graceful Degradation: If safetensors not available:

  • Still performs grouping and VRAM calculation
  • Uses class names instead of metadata
  • Shows warning on startup

Future Enhancements

Enhancement 1: Multi-GPU Tooltip

Current: Single tooltip for all GPUs
Proposed: Separate tooltip per GPU with per-GPU model list

Enhancement 2: Model Age Tracking

Current: Shows only current models
Proposed: Show "loaded 2m ago" timestamp

Enhancement 3: Offloaded Model Indicator

Current: Only shows GPU-resident models
Proposed: Show RAM-offloaded models with "(offloaded)" indicator

Enhancement 4: Model File Paths

Current: Shows model name only
Proposed: Show full file path in tooltip

Enhancement 5: More Metadata Fields

Current: Only uses model_type
Proposed: Extract and display architecture, base_model, etc.

  • Core Implementation: GPU_MEMORY_SCANNING.md - Original scanning approach
  • Widget Display: CONTROL_PANEL.md - Frontend tooltip rendering
  • API Endpoint: /swissarmyknife/profiler/loaded_models - REST API for model data
  • Node Tracking: profiler_core.py - Complete profiler implementation

Troubleshooting

Issue: No Models Shown

Cause: No CUDA modules in memory
Solution: Load a model and wait for node execution to complete

Issue: Shows Class Names Instead of Metadata

Cause: safetensors library not installed
Solution: pip3 install safetensors

Issue: Incorrect VRAM Numbers

Cause: Block swapping or model sharing
Solution: VRAM is per-GPU, shared layers counted once

Issue: Old Models Still Showing

Cause: Cache not invalidated
Solution: Wait 1 second or trigger VRAM change >100MB

Issue: Too Many Models Listed

Cause: Many small models loaded
Solution: Only top 10 shown, sorted by VRAM usage

Logging & Debugging

Console Output:

[SwissArmyKnife][Profiler] 📄 Captured model: Wan2_2-HIGH.safetensors (metadata: True)
[SwissArmyKnife][Profiler] 🔍 Found 603 CUDA modules, 5 top-level parents
[SwissArmyKnife][Profiler] ✅ Grouped into 5 parent models across 1 GPU(s)
[SwissArmyKnife][Profiler] GPU 0: 5 models
[SwissArmyKnife][Profiler]   - Wan2_2-T2V-A14B-HIGH (checkpoint, 2.1 GB, 145 layers)

Enable Debug Logging:

logger.setLevel(logging.DEBUG)

Commit Reference

Feature Branch: feat/Resource-monitor/CU-86b7mzbtx
Implementation Date: November 29, 2025
Key Changes:

  • Added safetensors import and metadata extraction
  • Enhanced _scan_gpu_models() with 5-phase approach
  • Added _capture_model_metadata() for filename tracking
  • Added helper methods for name extraction and matching
  • Fixed VRAM calculation using parent/child traversal
  • Limited display to top 10 models per GPU