import os import io import gc import re import json import base64 import random import torch import inspect import numpy as np from PIL import Image, ImageDraw from scipy.ndimage import gaussian_filter from .support.cqdm import cqdm from .support.gguf_layers import get_layer_count from .support.prompt_enhancer_preset import * import folder_paths import comfy.model_management as mm import comfy.utils import llama_cpp from llama_cpp import Llama from llama_cpp.llama_chat_format import ( Llava15ChatHandler, Llava16ChatHandler, MoondreamChatHandler, NanoLlavaChatHandler, Llama3VisionAlphaChatHandler, MiniCPMv26ChatHandler ) # 基础 Chat Handlers 定义 chat_handlers = ["None", "LLaVA-1.5", "LLaVA-1.6", "Moondream2", "nanoLLaVA", "llama3-Vision-Alpha", "MiniCPM-v2.6"] try: from llama_cpp.llama_chat_format import MTMDChatHandler chat_handlers += ["DeepSeek-OCR"] _MTMD = True except Exception: _MTMD = False try: from llama_cpp.llama_chat_format import Gemma3ChatHandler chat_handlers += ["Gemma3"] except Exception: Gemma3ChatHandler = None try: from llama_cpp.llama_chat_format import Gemma4ChatHandler chat_handlers += ["Gemma4"] except Exception: Gemma4ChatHandler = None try: from llama_cpp.llama_chat_format import Qwen25VLChatHandler chat_handlers += ["Qwen2.5-VL", "MinerU2.5-Pro"] except Exception: Qwen25VLChatHandler = None try: from llama_cpp.llama_chat_format import Qwen3VLChatHandler chat_handlers += ["Qwen3-VL", "Qwen3-VL-Thinking"] except Exception: Qwen3VLChatHandler = None try: from llama_cpp.llama_chat_format import Qwen35ChatHandler chat_handlers += ["Qwen3.5", "Qwen3.5-Thinking", "Qwen3.6", "Qwen3.6-Thinking", "Qwen3.8", "Qwen3.8-Thinking"] except Exception: Qwen35ChatHandler = None try: from llama_cpp.llama_chat_format import (GLM46VChatHandler, LFM2VLChatHandler, GLM41VChatHandler) chat_handlers += ["GLM-4.6V", "GLM-4.6V-Thinking", "GLM-4.1V-Thinking", "LFM2-VL"] except Exception: GLM46VChatHandler = None LFM2VLChatHandler = None GLM41VChatHandler = None try: from llama_cpp.llama_chat_format import LFM25VLChatHandler chat_handlers += ["LFM2.5-VL"] except Exception: LFM25VLChatHandler = None try: from llama_cpp.llama_chat_format import GraniteDoclingChatHandler chat_handlers += ["Granite-Docling"] except Exception: GraniteDoclingChatHandler = None try: from llama_cpp.llama_chat_format import MiniCPMv45ChatHandler chat_handlers += ["MiniCPM-v4.5", "MiniCPM-v4.5-Thinking"] except Exception: MiniCPMv45ChatHandler = None try: from llama_cpp.llama_chat_format import MiniCPMV46ChatHandler chat_handlers += ["MiniCPM-v4.6", "MiniCPM-v4.6-Thinking"] except Exception: MiniCPMV46ChatHandler = None try: from llama_cpp.llama_chat_format import PaddleOCRChatHandler chat_handlers += ["PaddleOCR-VL-1.5"] except Exception: PaddleOCRChatHandler = None try: from llama_cpp.llama_chat_format import Qwen3ASRChatHandler chat_handlers += ["Qwen3-ASR"] except Exception: Qwen3ASRChatHandler = None try: from llama_cpp.llama_chat_format import Step3VLChatHandler chat_handlers += ["Step3-VL"] except Exception: Step3VLChatHandler = None class AnyType(str): def __ne__(self, __value: object) -> bool: return False class LLAMA_CPP_STORAGE: llm = None chat_handler = None current_config = None current_embedding_mode = False messages = {} sys_prompts = {} @classmethod def ensure_embedding_mode(cls, enable_embeddings: bool): """ 根据底层 LlamaContext 源码精准适配的毫秒级热切换 """ if not cls.llm or not hasattr(cls.llm, "_ctx") or cls.llm._ctx is None: return # 如果当前模式已经符合要求,无需切换 if getattr(cls, "current_embedding_mode", None) == enable_embeddings: return print(f"[llama-cpp_vlm] 正在无缝热切换上下文模式 (embeddings={enable_embeddings})...") import llama_cpp ctx_class = type(cls.llm._ctx) # 1. 获取原生的 llama_context_params 结构体 if hasattr(cls.llm._ctx, "params") and cls.llm._ctx.params is not None: params = cls.llm._ctx.params else: params = llama_cpp.llama_context_default_params() # 2. 修改结构体中的 n_ctx 与 embeddings 状态 if hasattr(params, "n_ctx"): params.n_ctx = cls.current_config["n_ctx"] if hasattr(params, "embeddings"): params.embeddings = enable_embeddings # 3. 关闭上一个旧 Context (保留 4GB _model 权重) try: cls.llm._ctx.close() except Exception: pass # 4. 精准依据类定义进行实例化 (必须使用关键字参数传参) cls.llm._ctx = ctx_class( model=cls.llm._model, params=params, verbose=False ) cls.current_embedding_mode = enable_embeddings @classmethod def clean_state(cls, id=-1): if id == -1: cls.messages.clear() cls.sys_prompts.clear() else: cls.messages.pop(f"{id}", None) cls.sys_prompts.pop(f"{id}", None) @classmethod def clean(cls, all=False): try: if cls.llm: cls.llm.close() except Exception: pass try: if cls.chat_handler and hasattr(cls.chat_handler, "_exit_stack"): cls.chat_handler._exit_stack.close() except Exception: pass cls.llm = None cls.chat_handler = None cls.current_config = None if all: cls.clean_state() gc.collect() mm.soft_empty_cache() @classmethod def load_model(cls, config): def get_chat_handler(chat_handler): match chat_handler: case "Qwen3.5"|"Qwen3.5-Thinking"|"Qwen3.6"|"Qwen3.6-Thinking"|"Qwen3.8"|"Qwen3.8-Thinking": return Qwen35ChatHandler case "Qwen3-VL"|"Qwen3-VL-Thinking": return Qwen3VLChatHandler case "Qwen3-ASR": return Qwen3ASRChatHandler case "Qwen2.5-VL"|"MinerU2.5-Pro": return Qwen25VLChatHandler case "LLaVA-1.5": return Llava15ChatHandler case "LLaVA-1.6": return Llava16ChatHandler case "Moondream2": return MoondreamChatHandler case "nanoLLaVA": return NanoLlavaChatHandler case "llama3-Vision-Alpha": return Llama3VisionAlphaChatHandler case "MiniCPM-v2.6": return MiniCPMv26ChatHandler case "MiniCPM-v4.5"|"MiniCPM-v4.5-Thinking": return MiniCPMv45ChatHandler case "MiniCPM-v4.6"|"MiniCPM-v4.6-Thinking": return MiniCPMV46ChatHandler case "Gemma3": return Gemma3ChatHandler case "Gemma4": return Gemma4ChatHandler case "GLM-4.6V"|"GLM-4.6V-Thinking": return GLM46VChatHandler case "GLM-4.1V-Thinking": return GLM41VChatHandler case "LFM2-VL": return LFM2VLChatHandler case "LFM2.5-VL": return LFM25VLChatHandler case "Granite-Docling": return GraniteDoclingChatHandler case "DeepSeek-OCR": return MTMDChatHandler case "PaddleOCR-VL-1.5": return PaddleOCRChatHandler case "Step3-VL": return Step3VLChatHandler case "None": return None case _: raise ValueError(f'Unknown model type: "{chat_handler}"') cls.clean(all=True) cls.current_config = config.copy() model = config["model"] mmproj = config["mmproj"] chat_handler = config["chat_handler"] n_ctx = config["n_ctx"] vram_limit = config["vram_limit"] image_max_tokens = config["image_max_tokens"] image_min_tokens = config["image_min_tokens"] load_mtp = config["load_mtp"] n_gpu_layers = -1 model_path = os.path.join(folder_paths.models_dir, 'LLM', model) handler_cls = get_chat_handler(chat_handler) if vram_limit != -1: gguf_layers = get_layer_count(model_path) or 32 gguf_size = os.path.getsize(model_path) * 1.55 / (1024 ** 3) gguf_layer_size = gguf_size / gguf_layers if mmproj and mmproj != "None": mmproj_path = os.path.join(folder_paths.models_dir, 'LLM', mmproj) if chat_handler == "None": raise ValueError('"chat_handler" cannot be None when mmproj is used!') if handler_cls is None: raise RuntimeError(f"Chat handler '{chat_handler}' is not available or failed to import.") if vram_limit != -1: mmproj_size = os.path.getsize(mmproj_path) * 1.55 / (1024 ** 3) n_gpu_layers = max(1, int((vram_limit - mmproj_size) / gguf_layer_size)) print(f"[llama-cpp_vlm] Loading clip: {mmproj}") think_mode = "Thinking" in chat_handler kwargs = {"clip_model_path": mmproj_path, "verbose": False} if chat_handler in ["Qwen3-VL", "Qwen3-VL-Thinking"]: kwargs["force_reasoning"] = think_mode kwargs["image_max_tokens"] = image_max_tokens kwargs["image_min_tokens"] = image_min_tokens elif any(x in chat_handler for x in ["GLM-4.6V", "MiniCPM-v4.5", "MiniCPM-v4.6", "Qwen3.5", "Qwen3.6", "Qwen3.8"]): kwargs["enable_thinking"] = think_mode if _MTMD: kwargs["image_max_tokens"] = image_max_tokens kwargs["image_min_tokens"] = image_min_tokens try: cls.chat_handler = handler_cls(**kwargs) except Exception as e: raise RuntimeError(f"{e}\nPlease update llama-cpp-python from 'https://github.com/JamePeng/llama-cpp-python/releases'") else: if vram_limit != -1: n_gpu_layers = max(1, int(vram_limit / gguf_layer_size)) if handler_cls is not None: cls.chat_handler = handler_cls(verbose=False) else: cls.chat_handler = None print(f"[llama-cpp_vlm] Loading model: {model}") print(f"[llama-cpp_vlm] n_gpu_layers = {n_gpu_layers}") kwargs = { "model_path": model_path, "chat_handler": cls.chat_handler, "n_gpu_layers": n_gpu_layers, "n_ctx": n_ctx, "verbose": False, } if "load_mtp" in inspect.signature(Llama.__init__).parameters: kwargs["load_mtp"] = load_mtp else: if load_mtp: raise RuntimeError('"load_mtp" is unavailable! Please upgrade your llama-cpp-python.') cls.llm = Llama(**kwargs) any_type = AnyType("*") if not hasattr(mm, "unload_all_models_backup"): mm.unload_all_models_backup = mm.unload_all_models def patched_unload_all_models(*args, **kwargs): LLAMA_CPP_STORAGE.clean(all=True) result = mm.unload_all_models_backup(*args, **kwargs) return result mm.unload_all_models = patched_unload_all_models print("[llama-cpp_vlm] Model cleanup hook applied!") llm_extensions = ['.ckpt', '.pt', '.bin', '.pth', '.safetensors', '.gguf'] folder_paths.folder_names_and_paths["LLM"] = ([os.path.join(folder_paths.models_dir, "LLM")], llm_extensions) preset_prompts = { "Empty - Nothing": "", "Normal - Describe": "Describe this @.", "Prompt Style - Tags": "Your task is to generate a clean list of comma-separated tags for a text-to-@ AI, based *only* on the visual information in the @. Limit the output to a maximum of 50 unique tags. Strictly describe visual elements like subject, clothing, environment, colors, lighting, and composition. Do not include abstract concepts, interpretations, marketing terms, or technical jargon (e.g., no 'SEO', 'brand-aligned', 'viral potential'). The goal is a concise list of visual descriptors. Avoid repeating tags.", "Prompt Style - Simple": "Analyze the @ and generate a simple, single-sentence text-to-@ prompt. Describe the main subject and the setting concisely.", "Prompt Style - Detailed": "Generate a detailed, artistic text-to-@ prompt based on the @. Combine the subject, their actions, the environment, lighting, and overall mood into a single, cohesive paragraph of about 2-3 sentences. Focus on key visual details.", "Prompt Style - Extreme Detailed": "Generate an extremely detailed and descriptive text-to-@ prompt from the @. Create a rich paragraph that elaborates on the subject's appearance, textures of clothing, specific background elements, the quality and color of light, shadows, and the overall atmosphere. Aim for a highly descriptive and immersive prompt.", "Prompt Style - Cinematic": "Act as a master prompt engineer. Create a highly detailed and evocative prompt for an @ generation AI. Describe the subject, their pose, the environment, the lighting, the mood, and the artistic style (e.g., photorealistic, cinematic, painterly). Weave all elements into a single, natural language paragraph, focusing on visual impact.", "Creative - Detailed Analysis": "Describe this @ in detail, breaking down the subject, attire, accessories, background, and composition into separate sections.", "Creative - Summarize Video": "Summarize the key events and narrative points in this video.", "Creative - Short Story": "Write a short, imaginative story inspired by this @ or video.", "Creative - Refine & Expand Prompt": "Refine and enhance the following user prompt for creative text-to-@ generation. Keep the meaning and keywords, make it more expressive and visually rich. Output **only the improved prompt text itself**, without any reasoning steps, thinking process, or additional commentary.", "Vision - *Bounding Box": 'Locate every instance that belongs to the following categories: "#". Report bbox coordinates in {"bbox_2d": [x1, y1, x2, y2], "label": "string"} JSON format as a List.' } preset_tags = list(preset_prompts.keys()) def image2base64(image): img = Image.fromarray(image) buffered = io.BytesIO() img.save(buffered, format="JPEG", quality=85) return base64.b64encode(buffered.getvalue()).decode('utf-8') def parse_json(json_str): json_output = json_str.strip() if json_output.startswith("```json"): json_output = json_output[7:] if json_output.startswith("```"): json_output = json_output[3:] if json_output.endswith("```"): json_output = json_output[:-3] json_output = json_output.strip() try: parsed = json.loads(json_output) except Exception as e: raise ValueError(f"Unable to load JSON data!\n{e}") return parsed def scale_image(image: torch.Tensor, max_size: int = 128): img_np = np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8) img_pil = Image.fromarray(img_np) w, h = img_pil.size scale = min(max_size / max(w, h), 1.0) new_w, new_h = max(1, int(w * scale)), max(1, int(h * scale)) img_resized = img_pil.resize((new_w, new_h), Image.Resampling.LANCZOS) return np.array(img_resized) def qwen3bbox(image, json_data): img = Image.fromarray(np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) bboxes = [] if isinstance(json_data, dict): json_data = [json_data] for item in json_data: if not isinstance(item, dict) or "bbox_2d" not in item: continue x0, y0, x1, y1 = item["bbox_2d"] size = 1000.0 x0 = x0 / size * img.width y0 = y0 / size * img.height x1 = x1 / size * img.width y1 = y1 / size * img.height bboxes.append((x0, y0, x1, y1)) return bboxes def draw_bbox(image, json_data, mode): label_colors = {} img = Image.fromarray(np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) draw = ImageDraw.Draw(img) if isinstance(json_data, dict): json_data = [json_data] for item in json_data: if not isinstance(item, dict): continue label = item.get("label", item.get("text_content", "bbox")) if "bbox_2d" not in item: continue x0, y0, x1, y1 = item["bbox_2d"] if mode in ["Qwen3-VL", "Qwen2.5-VL"]: size = 1000.0 x0 = x0 / size * img.width y0 = y0 / size * img.height x1 = x1 / size * img.width y1 = y1 / size * img.height bbox = (x0, y0, x1, y1) if label not in label_colors: label_colors[label] = tuple(random.randint(80, 180) for _ in range(3)) color = label_colors[label] draw.rectangle(bbox, outline=color, width=4) text_y = max(0, y0 - 10) text_size = draw.textbbox((x0, text_y), str(label)) draw.rectangle([text_size[0], text_size[1]-2, text_size[2]+4, text_size[3]+2], fill=color) draw.text((x0+2, text_y), str(label), fill=(255,255,255)) return torch.from_numpy(np.array(img).astype(np.float32) / 255.0).unsqueeze(0) class llama_cpp_model_loader: @classmethod def INPUT_TYPES(s): all_llms = folder_paths.get_filename_list("LLM") model_list = [f for f in all_llms if "mmproj" not in f.lower()] mmproj_list = ["None"] + [f for f in all_llms if "mmproj" in f.lower()] return {"required": { "model": (model_list,), "mmproj": (mmproj_list, {"default": "None"}), "chat_handler": (chat_handlers, {"default": "None"}), "n_ctx": ("INT", { "default": 8192, "min": 1024, "max": 327680, "step": 128, "tooltip": "Context length limit." }), "vram_limit": ("INT", { "default": -1, "min": -1, "max": 1024, "step": 1, "tooltip": "VRAM usage limit in GB (-1 = no limit)\nReference range; actual usage may slightly exceed." }), "image_min_tokens": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 32}), "image_max_tokens": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 32}), "load_mtp": ("BOOLEAN", {"default": False}), } } RETURN_TYPES = ("LLAMACPPMODEL",) RETURN_NAMES = ("llama_model",) FUNCTION = "loadmodel" CATEGORY = "llama-cpp-vlm" def loadmodel(self, model, mmproj, chat_handler, n_ctx, vram_limit, image_min_tokens, image_max_tokens, load_mtp): custom_config = { "model": model, "mmproj": mmproj, "chat_handler": chat_handler, "n_ctx": n_ctx, "vram_limit": vram_limit, "image_min_tokens": image_min_tokens, "image_max_tokens": image_max_tokens, "load_mtp": load_mtp } if not LLAMA_CPP_STORAGE.llm or LLAMA_CPP_STORAGE.current_config != custom_config: print("[llama-cpp_vlm] Loading model...") LLAMA_CPP_STORAGE.load_model(custom_config) return (custom_config,) class llama_cpp_instruct_adv: @classmethod def INPUT_TYPES(s): return { "required": { "llama_model": ("LLAMACPPMODEL",), "preset_prompt": (preset_tags, {"default": preset_tags[1]}), "custom_prompt": ("STRING", {"default": "", "multiline": True, "placeholder": 'user_prompt\n\nFor preset hints marked with an "*", this will be used to fill the placeholder (e.g., Object names in BBox detection)\nOtherwise, this will override the preset prompts.'}), "system_prompt": ("STRING", {"multiline": True, "default": ""}), "inference_mode": (["one by one", "images", "video"], { "default": "one by one", "tooltip": "one by one: Process each item in the input list one by one (multi-image batch inside an item will be inferred together)\nimages: \tCombine ALL images across all list items into 1 single prompt\nvideo: \tTreat each image item in the list as a separate video clip" }), "max_frames": ("INT", { "default": 24, "min": 2, "max": 1024, "step": 1, "tooltip": 'Number of frames to sample evenly from input video.\n(for "video" mode only)' }), "max_size": ("INT", { "default": 256, "min": 128, "max": 16384, "step": 64, "tooltip": 'Max size of input images in "images" and "video" modes.' }), "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "step": 1}), "force_offload": ("BOOLEAN", { "default": False, "tooltip": "Unload the model after inference." }), "save_states": ("BOOLEAN", { "default": False, "tooltip": "Preserve the context of this conversation in RAM." }), }, "hidden": { "unique_id": "UNIQUE_ID", }, "optional": { "parameters": ("LLAMACPPARAMS",), "images": ("IMAGE",), "queue_handler": (any_type, {"tooltip": "Used to control the execution order of instruct nodes."}), }, } RETURN_TYPES = ("STRING", "STRING", "INT") RETURN_NAMES = ("output", "output_list", "state_uid") OUTPUT_IS_LIST = (False, True, False) INPUT_IS_LIST = True # 开启 LIST 支持 FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def sanitize_messages(self, messages): clean_messages = json.loads(json.dumps(messages)) for msg in clean_messages: content = msg.get("content") if isinstance(content, list): for item in content: if isinstance(item, dict) and item.get("type") == "image_url": item["image_url"]["url"] = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAADElEQVQImWP4//8/AAX+Av5Y8msOAAAAAElFTkSuQmCC" return clean_messages def process(self, llama_model, preset_prompt, custom_prompt, system_prompt, inference_mode, max_frames, max_size, seed, force_offload, save_states, unique_id, parameters=None, images=None, queue_handler=None): # 解包 INPUT_IS_LIST 参数 llama_model = llama_model[0] if isinstance(llama_model, list) else llama_model preset_prompt = preset_prompt[0] if isinstance(preset_prompt, list) else preset_prompt custom_prompt = custom_prompt[0] if isinstance(custom_prompt, list) else custom_prompt system_prompt = system_prompt[0] if isinstance(system_prompt, list) else system_prompt inference_mode = inference_mode[0] if isinstance(inference_mode, list) else inference_mode max_frames = max_frames[0] if isinstance(max_frames, list) else max_frames max_size = max_size[0] if isinstance(max_size, list) else max_size seed = seed[0] if isinstance(seed, list) else seed force_offload = force_offload[0] if isinstance(force_offload, list) else force_offload save_states = save_states[0] if isinstance(save_states, list) else save_states unique_id = unique_id[0] if isinstance(unique_id, list) else unique_id parameters = parameters[0] if isinstance(parameters, list) and parameters else parameters if not LLAMA_CPP_STORAGE.llm: LLAMA_CPP_STORAGE.load_model(llama_model) LLAMA_CPP_STORAGE.ensure_embedding_mode(False) if parameters is None: parameters = {} if _MTMD: parameters.pop("present_penalty", None) _uid = parameters.get("state_uid", None) _parameters = parameters.copy() _parameters.pop("state_uid", None) uid = str(unique_id).rpartition('.')[-1] if _uid in (None, -1) else str(_uid) last_sys_prompt = LLAMA_CPP_STORAGE.sys_prompts.get(f"{uid}", None) video_input = inference_mode == "video" system_prompts = "请将输入的图片序列当做视频而不是静态帧序列, " + system_prompt if video_input else system_prompt if last_sys_prompt != system_prompts: messages = [] LLAMA_CPP_STORAGE.clean_state(uid) LLAMA_CPP_STORAGE.sys_prompts[f"{uid}"] = system_prompts if system_prompts.strip(): messages.append({"role": "system", "content": system_prompts}) else: if save_states: try: print(f"[llama-cpp_vlm] Loading state and history id={uid}...") messages = LLAMA_CPP_STORAGE.messages.get(f"{uid}", []) except Exception: messages = [] else: messages = [] out1 = "" out2 = [] user_content = [] if custom_prompt.strip() and "*" not in preset_prompt: user_content.append({"type": "text", "text": custom_prompt}) else: p = preset_prompts[preset_prompt].replace("#", custom_prompt.strip()).replace("@", "video" if video_input else "image") user_content.append({"type": "text", "text": p}) # 过滤并按 list 里的每个 item 整理图片(保持 list 的每个 item 独立性) raw_image_list = [img for img in images if img is not None] if images is not None else [] if raw_image_list: curr_mmproj = LLAMA_CPP_STORAGE.current_config.get("mmproj") if LLAMA_CPP_STORAGE.current_config else None if LLAMA_CPP_STORAGE.chat_handler is None or curr_mmproj in [None, "None"]: raise ValueError("Image input detected, but the loaded model is not configured with a mmproj module.") # image_groups[i] 对应输入 list 里的第 i 个 item (可能包含单帧或 Batch 多帧) image_groups = [] for img_item in raw_image_list: if img_item.ndim == 3: image_groups.append([img_item]) elif img_item.ndim == 4: image_groups.append([img_item[i] for i in range(img_item.shape[0])]) # 1. ONE BY ONE 模式:遍历 list 里的每个 item,把该 item 里的所有图片放进同一次推理 if inference_mode == "one by one": print(f"[llama-cpp_vlm] [One-by-One Mode] Processing {len(image_groups)} list items individually...") tmp_list = [] for item_idx, item_frames in enumerate(cqdm(image_groups)): if mm.processing_interrupted(): raise mm.InterruptProcessingException() curr_user_content = json.loads(json.dumps(user_content)) for frame in item_frames: if len(item_frames) > 1: data = image2base64(scale_image(frame, max_size)) else: data = image2base64(np.clip(255.0 * frame.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) curr_user_content.append({ "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{data}"} }) curr_messages = messages + [{"role": "user", "content": curr_user_content}] output = LLAMA_CPP_STORAGE.llm.create_chat_completion(messages=curr_messages, seed=seed, **_parameters) text = output['choices'][0]['message']['content'].removeprefix(": ").lstrip() out2.append(text) if len(image_groups) > 1: tmp_list.append(f"====== Item {item_idx+1} ======") tmp_list.append(text) out1 = "\n\n".join(tmp_list) messages.append({"role": "user", "content": user_content}) # 2. IMAGES 模式:打平 list 里的所有 item,把所有图片合并在 1 次推理中 elif inference_mode == "images": all_frames = [frame for group in image_groups for frame in group] print(f"[llama-cpp_vlm] [Images Mode] Packing ALL {len(all_frames)} images into 1 single completion...") for frame in all_frames: if len(all_frames) > 1: data = image2base64(scale_image(frame, max_size)) else: data = image2base64(np.clip(255.0 * frame.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) user_content.append({ "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{data}"} }) messages.append({"role": "user", "content": user_content}) output = LLAMA_CPP_STORAGE.llm.create_chat_completion(messages=messages, seed=seed, **_parameters) raw_text = output['choices'][0]['message']['content'].removeprefix(": ").lstrip() # 使用正则剔除 ... 及其包含的所有内容 clean_text = re.sub(r'.*?(?:|$)', '', raw_text, flags=re.DOTALL).strip() out1 = clean_text out2 = [out1] # 3. VIDEO 模式:把 list 里的每个 item 各自当成一个视频独立推理 elif inference_mode == "video": print(f"[llama-cpp_vlm] [Video Mode] Processing {len(image_groups)} video clips...") tmp_list = [] for v_idx, video_frames in enumerate(cqdm(image_groups)): if mm.processing_interrupted(): raise mm.InterruptProcessingException() indices = np.linspace(0, len(video_frames) - 1, min(len(video_frames), max_frames), dtype=int) sampled_frames = [video_frames[i] for i in indices] curr_user_content = json.loads(json.dumps(user_content)) for frame in sampled_frames: data = image2base64(scale_image(frame, max_size)) curr_user_content.append({ "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{data}"} }) curr_messages = messages + [{"role": "user", "content": curr_user_content}] output = LLAMA_CPP_STORAGE.llm.create_chat_completion(messages=curr_messages, seed=seed, **_parameters) text = output['choices'][0]['message']['content'].removeprefix(": ").lstrip() out2.append(text) if len(image_groups) > 1: tmp_list.append(f"====== Video Clip {v_idx+1} ======") tmp_list.append(text) out1 = "\n\n".join(tmp_list) messages.append({"role": "user", "content": user_content}) else: # 纯文本模式 text_string = "".join([item["text"] for item in user_content if item.get("type") == "text"]) messages.append({"role": "user", "content": text_string}) output = LLAMA_CPP_STORAGE.llm.create_chat_completion(messages=messages, seed=seed, **_parameters) raw_text = output['choices'][0]['message']['content'].removeprefix(": ").lstrip() # 使用正则剔除 ... 及其包含的所有内容 clean_text = re.sub(r'.*?(?:|$)', '', raw_text, flags=re.DOTALL).strip() out1 = clean_text out2 = [out1] if save_states: print(f"[llama-cpp_vlm] Saving state id={uid}...") messages.append({"role": "assistant", "content": out1}) clear_message = self.sanitize_messages(messages) LLAMA_CPP_STORAGE.messages[f"{uid}"] = clear_message else: LLAMA_CPP_STORAGE.clean_state(uid) if force_offload: LLAMA_CPP_STORAGE.clean() else: if LLAMA_CPP_STORAGE.current_config and LLAMA_CPP_STORAGE.current_config["chat_handler"] in [ "Qwen3.5", "Qwen3.5-Thinking", "Qwen3.6", "Qwen3.6-Thinking", "Qwen3.8", "Qwen3.8-Thinking" ]: LLAMA_CPP_STORAGE.llm.n_tokens = 0 LLAMA_CPP_STORAGE.llm._ctx.memory_clear(True) if LLAMA_CPP_STORAGE.llm.is_hybrid and LLAMA_CPP_STORAGE.llm._hybrid_cache_mgr is not None: LLAMA_CPP_STORAGE.llm._hybrid_cache_mgr.clear() del messages gc.collect() return (out1, out2, uid) class llama_cpp_parameters: @classmethod def INPUT_TYPES(s): return { "required": { "max_tokens": ("INT", {"default": 1024, "min": 0, "max": 4096, "step": 1}), "top_k": ("INT", {"default": 30, "min": 0, "max": 1000, "step": 1}), "top_p": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01}), "min_p": ("FLOAT", {"default": 0.05, "min": 0.0, "max": 1.0, "step": 0.01}), "typical_p": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), "temperature": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 2.0, "step": 0.01}), "repeat_penalty": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), "frequency_penalty": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}), "present_penalty": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 2.0, "step": 0.01}), "mirostat_mode": ("INT", {"default": 0, "min": 0, "max": 2, "step": 1}), "mirostat_eta": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.01}), "mirostat_tau": ("FLOAT", {"default": 5.0, "min": 0.0, "max": 10.0, "step": 0.01}), "state_uid": ("INT", { "default": -1, "min": -1, "max": 999999, "step": 1, "tooltip": "Use a specific ID to save the conversation state.\n(-1 = use node's unique_id)" }), } } RETURN_TYPES = ("LLAMACPPARAMS",) RETURN_NAMES = ("parameters",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, **kwargs): return (kwargs,) class llama_cpp_clean_states: @classmethod def INPUT_TYPES(s): return { "required": { "any": (any_type,), "state_uid": ("INT", { "default": -1, "min": -1, "max": 999999, "step": 1, "tooltip": "Clear the saved state for a specific ID (-1 = clear all)" }), }, } RETURN_TYPES = (any_type,) RETURN_NAMES = ("any",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, any, state_uid): print(f"[llama-cpp_vlm] Cleaning up saved states {state_uid}...") LLAMA_CPP_STORAGE.clean_state(state_uid) return (any,) class llama_cpp_unload_model: @classmethod def INPUT_TYPES(s): return {"required": {"any": (any_type,)}} RETURN_TYPES = (any_type,) RETURN_NAMES = ("any",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, any): print("[llama-cpp_vlm] Unloading llama model...") LLAMA_CPP_STORAGE.clean() return (any,) class json_to_bbox: @classmethod def INPUT_TYPES(s): return { "required": { "json": ("STRING", {"forceInput": True}), "mode": (["simple", "Qwen3-VL", "Qwen2.5-VL"], {"default": "simple"}), "label": ("STRING", { "default": "", "multiline": False, "tooltip": "Select only the BBoxes with specific labels." }), }, "optional": { "image": ("IMAGE",), } } RETURN_TYPES = ("BBOX", "IMAGE") RETURN_NAMES = ("bboxes", "image_list") OUTPUT_IS_LIST = (True, True) INPUT_IS_LIST = True FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, json, mode, label, image=None): mode_val = mode[0] if isinstance(mode, list) and mode else "simple" label_val = label[0] if isinstance(label, list) and label else "" flat_images_list = [] original_structure = [] if image is not None: for img_batch in image: if img_batch is None: continue if img_batch.ndim == 3: flat_images_list.append(img_batch.unsqueeze(0)) original_structure.append(1) elif img_batch.ndim == 4: count = img_batch.shape[0] original_structure.append(count) for n in range(count): flat_images_list.append(img_batch[n:n+1]) total_images = len(flat_images_list) output_bboxes = [] processed_flat_results = [] for i, j in enumerate(json): bboxes = parse_json(j) if isinstance(bboxes, dict): bboxes = [bboxes] if label_val != "": bboxes = [ item for item in bboxes if isinstance(item, dict) and (item.get("label") == label_val or item.get("text_content") == label_val) ] if total_images > 0: curr_idx = i if i < total_images else (total_images - 1) curr_img = flat_images_list[curr_idx] try: res_img = draw_bbox(curr_img[0], bboxes, mode_val) if res_img.ndim == 3: res_img = res_img.unsqueeze(0) elif res_img.ndim == 4 and res_img.shape[0] > 1: res_img = res_img[0:1] processed_flat_results.append(res_img) except Exception as e: print(f"Error drawing on image {curr_idx}: {e}") processed_flat_results.append(curr_img) if mode_val in ["Qwen3-VL", "Qwen2.5-VL"]: if total_images == 0: raise ValueError("Image required for Qwen mode") curr_idx = i if i < total_images else (total_images - 1) bbox = qwen3bbox(flat_images_list[curr_idx][0], bboxes) else: bbox = [tuple(item["bbox_2d"]) for item in bboxes if isinstance(item, dict) and "bbox_2d" in item] output_bboxes.append(bbox) restructured_images_list = [] cursor = 0 for count in original_structure: chunk = processed_flat_results[cursor : cursor + count] if chunk: restructured_images_list.append(torch.cat(chunk, dim=0)) cursor += count return (output_bboxes, restructured_images_list) class SEG: def __init__(self, cropped_image, cropped_mask, confidence, crop_region, bbox, label, control_net_wrapper=None): self.cropped_image = cropped_image self.cropped_mask = cropped_mask self.confidence = confidence self.crop_region = crop_region self.bbox = bbox self.label = label self.control_net_wrapper = control_net_wrapper def __repr__(self): return (f"SEG(cropped_image={self.cropped_image}, cropped_mask=shape{self.cropped_mask.shape}, confidence={self.confidence}, bbox={self.bbox}, label='{self.label}'), control_net_wrapper={self.control_net_wrapper}") class bbox_to_segs: @classmethod def INPUT_TYPES(s): return { "required": { "bboxes": ("BBOX",), "image": ("IMAGE",), "dilation": ("INT", {"default": 10, "min": 0, "max": 200, "step": 1}), "feather": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}), } } RETURN_TYPES = ("SEGS",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, bboxes, image, dilation, feather): _batch_size, height, width, _channels = image.shape mask_shape = (height, width) seg_list = [] image_for_cropping = image[0] # 展平嵌套的 bbox flat_bboxes = [] for item in bboxes: if isinstance(item, (list, tuple)) and len(item) > 0 and isinstance(item[0], (list, tuple)): flat_bboxes.extend(item) else: flat_bboxes.append(item) for bbox in flat_bboxes: if not isinstance(bbox, (list, tuple)) or len(bbox) < 4: print(f"Warning: Skipping invalid bbox item: {bbox}") continue x1, y1, x2, y2 = map(int, bbox) x1_exp = x1 - dilation y1_exp = y1 - dilation x2_exp = x2 + dilation y2_exp = y2 + dilation crop_region = [x1_exp, y1_exp, x2_exp, y2_exp] crop_w = x2_exp - x1_exp crop_h = y2_exp - y1_exp if crop_h <= 0 or crop_w <= 0: print(f"Warning: Skipping bbox with invalid expanded size: {crop_region}") continue local_mask_np = np.zeros((crop_h, crop_w), dtype=np.float32) local_x1 = dilation local_y1 = dilation local_x2 = min(crop_w, local_x1 + (x2 - x1)) local_y2 = min(crop_h, local_y1 + (y2 - y1)) local_mask_np[local_y1:local_y2, local_x1:local_x2] = 1.0 if feather > 0: local_mask_np = gaussian_filter(local_mask_np, sigma=feather) cropped_mask_np = local_mask_np cropped_img_padded = torch.zeros((crop_h, crop_w, 3), dtype=image.dtype, device=image.device) src_x_start = max(0, x1_exp) src_y_start = max(0, y1_exp) src_x_end = min(width, x2_exp) src_y_end = min(height, y2_exp) dst_x_start = src_x_start - x1_exp dst_y_start = src_y_start - y1_exp dst_x_end = src_x_end - x1_exp dst_y_end = src_y_end - y1_exp if src_x_end > src_x_start and src_y_end > src_y_start: source_crop = image_for_cropping[src_y_start:src_y_end, src_x_start:src_x_end, :] cropped_img_padded[dst_y_start:dst_y_end, dst_x_start:dst_x_end, :] = source_crop cropped_image_tensor = cropped_img_padded.permute(2, 0, 1).unsqueeze(0) seg = SEG( cropped_image=cropped_image_tensor, cropped_mask=cropped_mask_np, confidence=np.array([0.9], dtype=np.float32), crop_region=crop_region, bbox=np.array(bbox, dtype=np.float32), label="bbox" ) seg_list.append(seg) segs = (mask_shape, seg_list) return (segs,) class bbox_to_mask: @classmethod def INPUT_TYPES(s): return { "required": { "bboxes": ("BBOX",), "image": ("IMAGE",), "dilation": ("INT", {"default": 10, "min": 0, "max": 200, "step": 1}), "feather": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}), } } RETURN_TYPES = ("MASK",) RETURN_NAMES = ("mask",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, bboxes, image, dilation, feather): masks = [] _batch_size, height, width, _channels = image.shape mask_shape = (height, width) combined_full_mask = torch.zeros(mask_shape, dtype=torch.float32, device=image.device) flat_bboxes = [] for item in bboxes: if isinstance(item, (list, tuple)) and len(item) > 0 and isinstance(item[0], (list, tuple)): flat_bboxes.extend(item) else: flat_bboxes.append(item) for bbox in flat_bboxes: if not isinstance(bbox, (list, tuple)) or len(bbox) < 4: print(f"Warning: Skipping invalid bbox item: {bbox}") continue x1, y1, x2, y2 = map(int, bbox) x1_exp = x1 - dilation y1_exp = y1 - dilation x2_exp = x2 + dilation y2_exp = y2 + dilation crop_w = x2_exp - x1_exp crop_h = y2_exp - y1_exp if crop_h <= 0 or crop_w <= 0: continue local_mask_np = np.zeros((crop_h, crop_w), dtype=np.float32) local_x1 = dilation local_y1 = dilation local_x2 = min(crop_w, local_x1 + (x2 - x1)) local_y2 = min(crop_h, local_y1 + (y2 - y1)) local_mask_np[local_y1:local_y2, local_x1:local_x2] = 1.0 if feather > 0: local_mask_np = gaussian_filter(local_mask_np, sigma=feather) current_full_mask_np = np.zeros(mask_shape, dtype=np.float32) x1_c, y1_c = max(0, x1_exp), max(0, y1_exp) x2_c, y2_c = min(width, x2_exp), min(height, y2_exp) if x2_c > x1_c and y2_c > y1_c: src_x1, src_y1 = max(0, -x1_exp), max(0, -y1_exp) src_x2 = src_x1 + (x2_c - x1_c) src_y2 = src_y1 + (y2_c - y1_c) current_full_mask_np[y1_c:y2_c, x1_c:x2_c] = local_mask_np[src_y1:src_y2, src_x1:src_x2] current_full_mask_tensor = torch.from_numpy(current_full_mask_np).to(image.device) combined_full_mask = torch.maximum(combined_full_mask, current_full_mask_tensor) masks.append(combined_full_mask.unsqueeze(0)) return (torch.cat(masks, dim=0),) class bboxes_to_bbox: @classmethod def INPUT_TYPES(s): return { "required": { "bboxes": ("BBOX",), "image_index": ("INT", {"default": 0, "min": 0, "max": 1000000, "step": 1}), "bbox_index": ("INT", { "default": 0, "min": -998, "max": 999, "step": 1, "tooltip": "BBox index in the image. Set to 999 to get all bboxes." }), } } RETURN_TYPES = ("BBOX",) RETURN_NAMES = ("bbox",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, bboxes, image_index, bbox_index): if not bboxes: return ([],) # 兼容 nested list 与 flat list if isinstance(bboxes[0], (list, tuple)) and len(bboxes[0]) > 0 and isinstance(bboxes[0][0], (list, tuple)): img_idx = min(max(0, image_index), len(bboxes) - 1) target_bboxes = bboxes[img_idx] else: target_bboxes = bboxes if not target_bboxes: return ([],) if bbox_index == 999: return (target_bboxes,) b_idx = min(max(0, bbox_index), len(target_bboxes) - 1) return ([target_bboxes[b_idx]],) def get_nested_value(data, dotted_key, default=None): keys = dotted_key.split('.') for key in keys: if isinstance(data, str): try: data = json.loads(data) except Exception: return default if isinstance(data, dict) and key in data: data = data[key] else: return default return data class parse_json_node: @classmethod def INPUT_TYPES(s): return { "required": { "input": ("STRING", {"forceInput": True}), }, "optional": { "key": ("STRING", {"default": ""}), "default": ("STRING", {"default": ""}), }, } RETURN_TYPES = (any_type, "STRING", "INT", "FLOAT", "BOOLEAN") RETURN_NAMES = ("any", "string", "int", "float", "boolean") FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, input, key="", default=""): if isinstance(input, str): input_list = [input] else: input_list = input res_any, res_str, res_int, res_float, res_bool = [], [], [], [], [] for json_str in input_list: if not key: val = json_str else: parsed_json = json_str.strip() if parsed_json.startswith("```json"): parsed_json = parsed_json[7:] if parsed_json.startswith("```"): parsed_json = parsed_json[3:] if parsed_json.endswith("```"): parsed_json = parsed_json[:-3] val = get_nested_value(parsed_json.strip(), key, default) res_any.append(val) res_str.append(str(val) if val is not None else "") try: res_int.append(int(val)) except Exception: res_int.append(0) try: res_float.append(float(val)) except Exception: res_float.append(0.0) try: if isinstance(val, bool): res_bool.append(val) else: res_bool.append(str(val).lower() == "true") except Exception: res_bool.append(False) if len(res_any) == 1: return (res_any[0], res_str[0], res_int[0], res_float[0], res_bool[0]) return (res_any, res_str, res_int, res_float, res_bool) class remove_code_block: @classmethod def INPUT_TYPES(s): return { "required": { "input": ("STRING", {"forceInput": True}), }, "optional": { "label": ("STRING", {"default": ""}), }, } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("output",) FUNCTION = "process" CATEGORY = "llama-cpp-vlm" def process(self, input, label=""): if isinstance(input, list): input_str = "\n".join(input) else: input_str = input val = input_str.strip() if label and val.startswith(f"```{label}"): val = val[len(f"```{label}"):] elif val.startswith("```"): lines = val.split("\n", 1) if len(lines) > 1: val = lines[1] else: val = lines[0].removeprefix("```") val = val.strip() if val.endswith("```"): val = val[:-3].strip() return (val,) class PromptEnhancerPreset: @classmethod def INPUT_TYPES(s): return { "required": { "preset": (["Qwen-Image [EN]", "Qwen-Image [ZH]", "Qwen-Image 2512 [EN]", "Qwen-Image 2512 [ZH]", "Qwen-Image-Edit", "Qwen-Image-Edit 2509", "Qwen-Image-Edit 2511", "Z-Image Turbo", "Flux.2 T2I", "Flux.2 I2I", "Wan T2V [EN]", "Wan T2V [ZH]", "Wan I2V [EN]", "Wan I2V [ZH]", "Wan I2V Full-Auto [EN]", "Wan I2V Full-Auto [ZH]", "Wan FLF2V [EN]", "Wan FLF2V [ZH]"], ) } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("system_prompt",) FUNCTION = "main" CATEGORY = "llama-cpp-vlm" def main(self, preset): match preset: case "Qwen-Image [EN]": return (QWEN_IMAGE_EN,) case "Qwen-Image [ZH]": return (QWEN_IMAGE_ZH,) case "Qwen-Image 2512 [EN]": return (QWEN_IMAGE_2512_EN,) case "Qwen-Image 2512 [ZH]": return (QWEN_IMAGE_2512_ZH,) case "Qwen-Image-Edit": return (QWEN_IMAGE_EDIT,) case "Qwen-Image-Edit 2509": return (QWEN_IMAGE_EDIT_2509,) case "Qwen-Image-Edit 2511": return (QWEN_IMAGE_EDIT_2511,) case "Z-Image Turbo": return (ZIMAGE_TURBO,) case "Flux.2 T2I": return (FLUX2_T2I,) case "Flux.2 I2I": return (FLUX2_I2I,) case "Wan T2V [EN]": return (WAN_T2V_EN,) case "Wan T2V [ZH]": return (WAN_T2V_ZH,) case "Wan I2V [EN]": return (WAN_I2V_EN,) case "Wan I2V [ZH]": return (WAN_I2V_ZH,) case "Wan I2V Full-Auto [EN]": return (WAN_I2V_EMPTY_EN,) case "Wan I2V Full-Auto [ZH]": return (WAN_I2V_EMPTY_ZH,) case "Wan FLF2V [EN]": return (WAN_FLF2V_EN,) case "Wan FLF2V [ZH]": return (WAN_FLF2V_ZH,) case _: raise ValueError(f'Unknown preset: "{preset}"') class llama_cpp_text_encoder: """ 统一的 Llama-cpp Text Encoder 节点。 支持替代 Z-Image, Lumina2, Qwen-Image, MiniMax T2V, Boogu-Image, JoyImage, Mage-Flow 等原生文本编码器。 """ PRESETS = { "Boogu-Image": { "template": "<|im_start|>system\nYou are a helpful assistant that generates high-quality images based on user instructions. The instructions are as follows.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n", "layer_idx": -1, "trim_template": False, }, "JoyImage": { "template": "<|im_start|>system\n \\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n", "layer_idx": -1, "trim_template": True, }, "Lumina2": { "template": "{}", "layer_idx": -2, "trim_template": False, }, "Mage-Flow": { "template": "<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n", "layer_idx": -1, "trim_template": True, }, "MiniMax-T2V": { "template": "{}", "layer_idx": 49, "trim_template": False, "is_minimax_t2v": True, }, "Qwen-Image": { "template": "<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n", "layer_idx": -1, "trim_template": True, }, "Z-Image": { "template": "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n", "layer_idx": -2, "trim_template": False, }, } @classmethod def INPUT_TYPES(s): return { "required": { "llama_model": ("LLAMACPPMODEL",), "prompt": ("STRING", {"multiline": True, "default": "", "dynamicPrompts": True}), "type": (list(s.PRESETS.keys()), {"default": "Z-Image"}), "force_offload": ("BOOLEAN", { "default": False, "tooltip": "Unload the model after inference." }), } } RETURN_TYPES = ("CONDITIONING",) RETURN_NAMES = ("conditioning",) FUNCTION = "encode" CATEGORY = "llama-cpp-vlm" def _extract_native_embeddings(self, llm, prompt_text, target_layer, tokens): import ctypes # 1. 目标层换算 (负数层转正数) model = getattr(llm, "_model", None) or getattr(llm, "model", None) or llm n_layers = getattr(model, "n_layer", None) or getattr(llm, "n_layer", None) if callable(n_layers): n_layers = n_layers() pos_layer = (n_layers + target_layer) if (n_layers is not None and target_layer < 0) else target_layer # 尝试通过原生接口设置目标层 if hasattr(model, "set_target_layer_ids") and callable(model.set_target_layer_ids): try: model.set_target_layer_ids([pos_layer]) except Exception: pass elif hasattr(model, "target_layer_ids"): if callable(model.target_layer_ids): try: t_ids = model.target_layer_ids() if isinstance(t_ids, list): t_ids.clear() t_ids.append(pos_layer) except Exception: pass num_tokens = len(tokens) # 2. 安全清理状态 if hasattr(llm, "n_tokens"): llm.n_tokens = 0 if hasattr(llm, "_ctx"): if hasattr(llm._ctx, "kv_cache_clear"): llm._ctx.kv_cache_clear() elif hasattr(llm._ctx, "memory_clear"): llm._ctx.memory_clear(True) # 3. 执行推理计算 llm.eval(tokens) # 4. 从上下文中提取深层特征 ctx_ptr = getattr(llm, "ctx", None) or getattr(getattr(llm, "_ctx", None), "ctx", None) n_embd = llm.n_embd() if callable(getattr(llm, "n_embd", None)) else getattr(llm, "n_embd", 4096) emb_np = None # 优先提取指定层激活状态 for fn_name in ["llama_get_layer_state", "llama_get_layer_embeddings", "llama_get_layer_output"]: if hasattr(llama_cpp, fn_name): fn = getattr(llama_cpp, fn_name) try: ptr = fn(ctx_ptr, ctypes.c_int(pos_layer)) if ptr: emb_np = np.ctypeslib.as_array(ptr, shape=(num_tokens, n_embd)).copy() break except Exception: pass # 备选提取 if emb_np is None: if hasattr(llama_cpp, "llama_get_embeddings_ith"): token_embeds = [] for i in range(num_tokens): ptr = llama_cpp.llama_get_embeddings_ith(ctx_ptr, ctypes.c_int(i)) if ptr: token_embeds.append(np.ctypeslib.as_array(ptr, shape=(n_embd,)).copy()) if len(token_embeds) == num_tokens: emb_np = np.stack(token_embeds, axis=0) if emb_np is None and hasattr(llama_cpp, "llama_get_embeddings"): ptr = llama_cpp.llama_get_embeddings(ctx_ptr) if ptr: emb_np = np.ctypeslib.as_array(ptr, shape=(num_tokens, n_embd)).copy() if emb_np is None: raise RuntimeError(f"提取 Layer {pos_layer} 失败!请确保模型加载时启用了 'embeddings=True'。") # 5. 转为 Tensor 并规范维度为 [1, seq_len, hidden_dim] emb = torch.tensor(emb_np, dtype=torch.float32) if emb.ndim == 2: emb = emb.unsqueeze(0) elif emb.ndim == 1: emb = emb.unsqueeze(0).unsqueeze(0) return emb def encode(self, llama_model, prompt, type, force_offload): if not LLAMA_CPP_STORAGE.llm: LLAMA_CPP_STORAGE.load_model(llama_model) LLAMA_CPP_STORAGE.ensure_embedding_mode(True) llm = LLAMA_CPP_STORAGE.llm cfg = self.PRESETS[type] target_layer = cfg["layer_idx"] prompt_text = cfg["template"].format(prompt) if "{}" in cfg["template"] else prompt # 【关键修复 1】:必须加 special=True,否则 <|im_start|> 无法被解析为 151644 tokens = llm.tokenize(prompt_text.encode("utf-8"), add_bos=False, special=True) if len(tokens) == 0: tokens = [151643] # MiniMax 严格要求纯净文本,不能有任何 BOS (151643 / 151644 / 1) if cfg.get("is_minimax_t2v", False) and len(tokens) > 1: if tokens[0] in [151643, 151644, 1]: tokens = tokens[1:] # 剥离开头的 BOS Token # 提取特征 hidden_tensor = self._extract_native_embeddings(llm, prompt_text, target_layer, tokens) # 【关键修复 2】:更鲁棒的裁切验证 if cfg.get("trim_template", False) and len(tokens) > 3: trim_idx = 0 count_im_start = 0 for i in range(len(tokens) - 2): if tokens[i] == 151644: # <|im_start|> count_im_start += 1 if count_im_start == 2: # 找到了 user block 的开始 if tokens[i+1] == 872 and tokens[i+2] == 198: # user \n trim_idx = i + 3 else: trim_idx = i + 1 break # 执行特征截断 if trim_idx > 0 and hidden_tensor.shape[1] > trim_idx: hidden_tensor = hidden_tensor[:, trim_idx:, :] else: print(f"\n[llama-cpp_vlm] Warning: Trim failed! Token IDs: {tokens[:10]}...") seq_len = hidden_tensor.shape[1] pooled = torch.zeros((hidden_tensor.shape[0], hidden_tensor.shape[-1]), dtype=torch.float32) # 构造 Conditioning 字典 cond_dict = {"pooled_output": pooled} # MiniMax T2V 专属标记 if cfg.get("is_minimax_t2v", False): cond_dict["minimax_token_tags"] = torch.ones(seq_len, dtype=torch.long) print(f"\n[MiniMax Diagnostic] Tensor Shape: {hidden_tensor.shape}, Mean: {hidden_tensor.mean().item():.4f}, Std: {hidden_tensor.std().item():.4f}\n") conditioning = [[hidden_tensor, cond_dict]] if force_offload: LLAMA_CPP_STORAGE.clean() return (conditioning,) NODE_CLASS_MAPPINGS = { "llama_cpp_model_loader": llama_cpp_model_loader, "llama_cpp_instruct_adv": llama_cpp_instruct_adv, "llama_cpp_parameters": llama_cpp_parameters, "llama_cpp_unload_model": llama_cpp_unload_model, "llama_cpp_clean_states": llama_cpp_clean_states, "parse_json_node": parse_json_node, "json_to_bbox": json_to_bbox, "bbox_to_segs": bbox_to_segs, "bbox_to_mask": bbox_to_mask, "bboxes_to_bbox": bboxes_to_bbox, "remove_code_block": remove_code_block, "PromptEnhancerPreset": PromptEnhancerPreset, "llama_cpp_text_encoder": llama_cpp_text_encoder, } NODE_DISPLAY_NAME_MAPPINGS = { "llama_cpp_model_loader": "Llama-cpp Model Loader", "llama_cpp_instruct_adv": "Llama-cpp Instruct", "llama_cpp_parameters": "Llama-cpp Parameters", "llama_cpp_unload_model": "Llama-cpp Unload Model", "llama_cpp_clean_states": "Llama-cpp Clean States", "parse_json_node": "Parse JSON", "json_to_bbox": "JSON to BBoxes", "bbox_to_segs": "BBoxes to SEGS", "bbox_to_mask": "BBoxes to MASK", "bboxes_to_bbox": "BBoxes to BBox", "remove_code_block": "Unpack Code Block", "PromptEnhancerPreset": "Prompt Enhancer Preset", "llama_cpp_text_encoder": "Llama-cpp Text Encoder (BETA)", }