34 Commits
Author SHA1 Message Date
Johan Mellin a36989c473 Update README.md 2025-07-20 14:17:01 +02:00
Johan Mellin 1f1e6f830e Update README.md 2025-07-20 14:16:25 +02:00
Johan Mellin f1f0f2cd9d Update README.md 2025-07-20 14:15:58 +02:00
Johan Mellin 528c2512be Update README.md 2025-07-20 14:09:12 +02:00
Johan Mellin e0566730ee Merge pull request #9 from ComfyNodePRs/update-publish-yaml
Update Github Action for Publishing to Comfy Registry
2025-05-08 12:35:48 +02:00
Nojahhh 68907256aa added Qwen non-vision model to model list 2025-03-06 22:11:30 +01:00
Nojahhh f849042536 added support for Qwen2.5 3B and 7B models 2025-03-04 12:19:17 +01:00
Nojahhh 8a1eb1a213 separated clearCache and unloadModel pipeline functions and updated examples 2025-01-29 00:38:21 +01:00
snomiao ebcc742c10 chore(publish): update workflow permissions and conditions for node publishing 2025-01-25 07:37:00 +00:00
Nojahhh 3df69d6640 changed unload_model default to False (because of Comfy smart memory management 2024-12-17 21:52:22 +01:00
Johan Mellin b5a847b320 Update README.md 2024-12-04 23:12:07 +01:00
Johan Mellin 51522174e1 Update README.md 2024-12-04 23:11:43 +01:00
Johan Mellin e97cfa17c4 Update README.md 2024-12-04 21:31:53 +01:00
Johan Mellin b9052f6d82 Update README.md 2024-12-04 21:29:48 +01:00
Johan Mellin 30b64d5856 Update README.md 2024-12-04 21:29:12 +01:00
Johan Mellin 39fba4882f Update README.md 2024-12-04 21:28:46 +01:00
Johan Mellin 9ddafe51a4 Update README.md 2024-12-04 21:28:29 +01:00
Nojahhh d73d3415c7 updated README.md with information about AutoGPTQ 2024-12-04 21:27:48 +01:00
Nojahhh 2f0fd328e0 Merge branch 'main' of https://github.com/Nojahhh/ComfyUI_GLM4_Wrapper 2024-12-04 21:24:13 +01:00
Nojahhh 115f04bacb added seed input to prompt enchancer and inferer nodes, removed unpolished reinit solution 2024-12-04 21:24:07 +01:00
Johan Mellin e2cee57bd7 Update README.md 2024-12-01 22:42:41 +01:00
Nojahhh a093065db4 fixed typo in infer node 2024-12-01 22:39:15 +01:00
Johan Mellin 1021d55333 Update README.md 2024-11-12 14:33:00 +01:00
Nojahhh e2eef3bbb8 clarified quant option when using GPTQ models of vision model 2024-10-20 23:42:07 +02:00
Nojahhh f97ddf16d1 fixed bug for 3-bit version of vision model, updated requirements and README 2024-10-20 23:38:53 +02:00
Johan Mellin d3198acdfd Merge pull request #5 from ComfyNodePRs/pyproject
Add pyproject.toml for Custom Node Registry
2024-10-03 18:18:56 +02:00
Johan Mellin 58ec0f7c0d Merge pull request #6 from ComfyNodePRs/publish
Add Github Action for Publishing to Comfy Registry
2024-10-03 18:18:35 +02:00
Johan Mellin de85ae8961 Update pyproject.toml 2024-10-03 18:18:04 +02:00
snomiao 57957b84ac chore(pyproject): Add pyproject.toml for Custom Node Registry 2024-10-03 16:01:15 +00:00
snomiao f9f06b4b51 chore(publish): Add Github Action for Publishing to Comfy Registry 2024-10-03 16:01:14 +00:00
Johan Mellin f91a86078f fixed typo in README.md 2024-10-03 02:33:06 +02:00
Nojahhh 016879ef89 updated examples based on new gptq models. updated default quant value for glm-4v-9b to 4 instead of 8. updated README.md accordingly 2024-10-03 02:32:14 +02:00
Johan Mellin 9fb3bc194a Update glm-4-inference.json 2024-10-03 02:24:23 +02:00
Johan Mellin 25b9e2f611 Merge pull request #4 from Nojahhh/dev
Added support for new quantized models (alexwww94) GPTQ 3-/4-bit
2024-10-03 02:05:37 +02:00
7 changed files with 416 additions and 174 deletions
+26
View File
@@ -0,0 +1,26 @@
name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- main
- master
paths:
- "pyproject.toml"
permissions:
issues: write
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'Nojahhh' }}
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@v1
with:
## Add your own personal access token to your Github Repository secrets and reference it here.
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
+48 -14
View File
@@ -1,5 +1,7 @@
# ComfyUI GLM-4 Wrapper
**NOTE:** You can find this wrapper in [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager). Search for GLM-4 and install it through there.
This repository contains custom nodes for ComfyUI, specifically designed to enhance and infer prompts using the GLM-4 model on local hardware.
The nodes leverage the GLM-4 model to generate detailed and descriptive image/video captions or enhance user-provided prompts, among regular inference.
@@ -10,14 +12,35 @@ All models will be downloaded automatically through HuggingFace.co. `THUDM/glm-4
The nodes containes an "unload_model" option which frees up VRAM space and makes it suitable for workflows that requires larger VRAM space, like FLUX.1-dev and CogVideoX-5b(-I2V).
The prompt enhancer is based on this example from THUDM [convert_demo.py](https://github.com/THUDM/CogVideo/blob/main/inference/convert_demo.py).
Thier demo is only for usage through OpenAI API and I wanted to build something local.
The prompt enhancer is initially based on this example from THUDM [convert_demo.py](https://github.com/THUDM/CogVideo/blob/main/inference/convert_demo.py) but has been further developed over time.
Their demo is only for usage through OpenAI API and I wanted to build something local.
Hope you will enjoy your enhanced prompts and inference capabilities of these models. They are great!
## Update 2025-03-04
Added support for Qwen 2.5 models.
Models:
`Qwen2.5-VL-3B-Instruct` (Visual, thus supports image + text)
`Qwen2.5-VL-7B-Instruct` (Visual, thus supports image + text)
`Qwen2.5-3B-Instruct` (Language, only supports text)
## Update 2024-10-03
Added support for quantized models. They are performing exceptionally well. Check metrics below.
Added support for quantized models. They perform exceptionally well. Check metrics below.
**Important**:
To be able to use these models you will need to install AutoGPTQ library.
`pip install auto-gptq`
If you are on Windows you will need to install this from source to enable CUDA extensions.
[AutoGPTQ](https://github.com/AutoGPTQ/AutoGPTQ/)
Model `alexwww94/glm-4v-9b-gptq-4bit` is significatly more lightweight than the original and will hold ~8.5 GB of hdd space.
@@ -34,6 +57,10 @@ Model `alexwww94/glm-4v-9b-gptq-3bit` is even more lightweight and will hold ~7.
## Installation
Easiest way to install this is through [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager)
You can also install this manually:
1. Navigate to ComfyUI custom nodes:
```bash
cd /your/path/to/ComfyUI/ComfyUI/custom_nodes/
@@ -48,7 +75,7 @@ Model `alexwww94/glm-4v-9b-gptq-3bit` is even more lightweight and will hold ~7.
```
4. Install the required dependencies:
```bash
../../python_embeded python.exe -m pip install -r requirements.txt
../../python_embeded python -m pip install -r requirements.txt
```
## Usage
@@ -60,8 +87,11 @@ The `GLM4ModelLoader` class is responsible for loading GLM-4 models. It supports
#### Input Types
- **model**: Choose the GLM-4 model to load. Model will download automatically from HuggingFace.co
- **precision**: Precision type (`fp16`, `fp32`, `bf16`). `THUDM/glm-4v-9b` requires `bf16` and is set to run in 8-bit by default based on it's size. `alexwww94/glm-4v-9b-gptq-4bit` requires `bf16` and is set to run in 4-bit by default. `alexwww94/glm-4v-9b-gptq-3bit` requires `bf16` and is set to run in 3-bit by default.
- **quantization**: Set the number of bits for quantization (`4`, `8`, `16`).
- **precision**: Precision type (`fp16`, `fp32`, `bf16`).
`THUDM/glm-4v-9b` requires `bf16` and is set to run in 4-bit by default based on it's size.
`alexwww94/glm-4v-9b-gptq-4bit` requires `bf16` and is set to run in 4-bit by default.
`alexwww94/glm-4v-9b-gptq-3bit` requires `bf16` and is set to run in 3-bit by default.
- **quantization**: Set the number of bits for quantization (`4`, `8`, `16`). Default value of `4`. (This option is bypassed when using the GPTQ-models).
#### Output
@@ -80,8 +110,9 @@ Enhances a given prompt using the GLM-4 model.
- **top_k**: Top-k parameter for sampling.
- **top_p**: Top-p parameter for sampling.
- **repetition_penalty**: Repetition penalty for sampling.
- **image** (optional): Image to enhance the prompt. Only works with `THUDM/glm-4v-9b` and `alexwww94/glm-4v-9b-gptq-4bit` and `alexwww94/glm-4v-9b-gptq-3bit`.
- **image** (optional): Image to enhance the prompt. Only works with `THUDM/glm-4v-9b`, `alexwww94/glm-4v-9b-gptq-4bit` and `alexwww94/glm-4v-9b-gptq-3bit`.
- **unload_model**: Unload the model after use.
- **seed** (optional): Seed for reproducability.
#### Output
@@ -101,8 +132,9 @@ Performs inference using the GLM-4 model.
- **top_k**: Top-k parameter for sampling.
- **top_p**: Top-p parameter for sampling.
- **repetition_penalty**: Repetition penalty for sampling.
- **image** (optional): Image to use as input for inferencing. Only works with `THUDM/glm-4v-9b` and `alexwww94/glm-4v-9b-gptq-4bit` and `alexwww94/glm-4v-9b-gptq-3bit`.
- **image** (optional): Image to use as input for inferencing. Only works with `THUDM/glm-4v-9b`, `alexwww94/glm-4v-9b-gptq-4bit` and `alexwww94/glm-4v-9b-gptq-3bit`.
- **unload_model**: Unload the model after use.
- **seed** (optional): Seed for reproducability.
#### Output
@@ -136,10 +168,10 @@ The following GLM-4 models are supported by this wrapper:
| `THUDM/LongWriter-glm4-9b` | 9B | `fp16`, `fp32`, `bf16` |
### Notes:
- `THUDM/glm-4v-9b` requires `bf16` precision and is default 8-bit quantization due to its size and the typical VRAM limitations of consumer-grade GPUs (often 24GB or less).
- `THUDM/glm-4v-9b` requires `bf16` precision and is default 4-bit quantization due to its size and the typical VRAM limitations of consumer-grade GPUs (often 24GB or less).
- `alexwww94/glm-4v-9b-gptq-4bit` requires `bf16` and is default 4-bit.
- `alexwww94/glm-4v-9b-gptq-3bit` requires `bf16` and is default 3-bit.
- Only `THUDM/glm-4v-9b` and `alexwww94/glm-4v-9b-gptq-4bit` and `alexwww94/glm-4v-9b-gptq-3bit` models are able to handle image input.
- Only `THUDM/glm-4v-9b`, `alexwww94/glm-4v-9b-gptq-4bit` and `alexwww94/glm-4v-9b-gptq-3bit` models are able to handle image input.
## Example Usage
@@ -159,13 +191,14 @@ enhancer = GLM4PromptEnhancer()
enhanced_prompt = enhancer.enhance_prompt(
GLMPipeline=pipeline,
prompt="A beautiful sunrise over the mountains",
max_tokens=200,
max_new_tokens=200,
temperature=0.1,
top_k=40,
top_p=0.7,
repetition_penalty=1.1,
image=None, # PIL Image
unload_model=True
unload_model=True,
seed=42
)
print(enhanced_prompt)
```
@@ -185,13 +218,14 @@ output_text = inference.infer(
GLMPipeline=pipeline,
system_prompt="Describe the scene in detail:",
user_prompt="A bustling city street at night",
max_tokens=250,
max_new_tokens=250,
temperature=0.7,
top_k=50,
top_p=1,
repetition_penalty=1.0,
image=None,
unload_model=True
unload_model=True,
seed=42
)
print(output_text)
```
+42 -42
View File
@@ -79,39 +79,6 @@
"image"
]
},
{
"id": 8,
"type": "GLM-4 Model Loader",
"pos": {
"0": 390,
"1": 270
},
"size": {
"0": 315,
"1": 106
},
"flags": {},
"order": 1,
"mode": 0,
"inputs": [],
"outputs": [
{
"name": "GLMPipeline",
"type": "GLMPipeline",
"links": [
12
]
}
],
"properties": {
"Node name for S&R": "GLM-4 Model Loader"
},
"widgets_values": [
"THUDM/glm-4v-9b",
"bf16",
"8"
]
},
{
"id": 10,
"type": "GLM-4 Inferencing",
@@ -119,10 +86,10 @@
"0": 760,
"1": 270
},
"size": [
400,
340
],
"size": {
"0": 400,
"1": 340
},
"flags": {},
"order": 2,
"mode": 0,
@@ -153,14 +120,47 @@
"Node name for S&R": "GLM-4 Inferencing"
},
"widgets_values": [
"What is the name of the celebrity playing this character? Explain who she is and where she was born and what her future might look like.",
"You are a very intelligent bot who can classify everything from humans to molecules.",
"What is the name of the celebrity playing this character? Explain who she is and where she was born and what her future might look like.",
250,
0.7,
50,
1,
1,
true
false
]
},
{
"id": 8,
"type": "GLM-4 Model Loader",
"pos": {
"0": 390,
"1": 270
},
"size": {
"0": 315,
"1": 106
},
"flags": {},
"order": 1,
"mode": 0,
"inputs": [],
"outputs": [
{
"name": "GLMPipeline",
"type": "GLMPipeline",
"links": [
12
]
}
],
"properties": {
"Node name for S&R": "GLM-4 Model Loader"
},
"widgets_values": [
"alexwww94/glm-4v-9b-gptq-4bit",
"bf16",
"4"
]
}
],
@@ -194,10 +194,10 @@
"config": {},
"extra": {
"ds": {
"scale": 0.8264462809917361,
"scale": 1.3310000000000004,
"offset": [
157.57704486550713,
87.84898669179454
-236.1440996429332,
-134.80615416843378
]
}
},
+41 -41
View File
@@ -112,39 +112,6 @@
"Tokyo night, busy street, neon lights"
]
},
{
"id": 10,
"type": "GLM-4 Model Loader",
"pos": {
"0": 390,
"1": 130
},
"size": {
"0": 315,
"1": 106
},
"flags": {},
"order": 2,
"mode": 0,
"inputs": [],
"outputs": [
{
"name": "GLMPipeline",
"type": "GLMPipeline",
"links": [
11
]
}
],
"properties": {
"Node name for S&R": "GLM-4 Model Loader"
},
"widgets_values": [
"THUDM/glm-4v-9b",
"bf16",
"8"
]
},
{
"id": 9,
"type": "GLM-4 Prompt Enhancer",
@@ -152,10 +119,10 @@
"0": 760,
"1": 130
},
"size": [
342.5999755859375,
222
],
"size": {
"0": 342.5999755859375,
"1": 222
},
"flags": {},
"order": 3,
"mode": 0,
@@ -200,7 +167,40 @@
40,
0.7,
1.1,
true
false
]
},
{
"id": 10,
"type": "GLM-4 Model Loader",
"pos": {
"0": 390,
"1": 130
},
"size": {
"0": 315,
"1": 106
},
"flags": {},
"order": 2,
"mode": 0,
"inputs": [],
"outputs": [
{
"name": "GLMPipeline",
"type": "GLMPipeline",
"links": [
11
]
}
],
"properties": {
"Node name for S&R": "GLM-4 Model Loader"
},
"widgets_values": [
"alexwww94/glm-4v-9b-gptq-4bit",
"bf16",
"4"
]
}
],
@@ -242,10 +242,10 @@
"config": {},
"extra": {
"ds": {
"scale": 0.8264462809917361,
"scale": 1.3310000000000004,
"offset": [
272.52704486550704,
56.38898669179459
-197.07572999605105,
-4.828693612460846
]
}
},
+241 -75
View File
@@ -5,7 +5,7 @@
import torch
import comfy.model_management as mm
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from transformers import Qwen2_5_VLForConditionalGeneration, AutoModelForCausalLM, AutoTokenizer, AutoProcessor, BitsAndBytesConfig, set_seed
from PIL import Image
import logging
import numpy as np
@@ -15,6 +15,13 @@ import gc
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger(__name__)
def tensor_to_pil(image_tensor, batch_index=0) -> Image:
# Convert tensor of shape [batch, height, width, channels] at the batch_index to PIL Image
image_tensor = image_tensor[batch_index].unsqueeze(0)
i = 255.0 * image_tensor.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8).squeeze())
return img
class GLMPipeline:
def __init__(self):
self.tokenizer = None
@@ -22,24 +29,30 @@ class GLMPipeline:
self.model_name = None
self.precision = None
self.quantization = None
self.processor = None
self.parent = None
def clearCache(self):
mm.soft_empty_cache()
torch.cuda.empty_cache()
torch.cuda.synchronize()
torch._C._cuda_clearCublasWorkspaces()
gc.collect()
def unloadModel(self):
if self.transformer:
self.transformer.cpu()
del self.transformer
if self.tokenizer:
del self.tokenizer
torch.cuda.empty_cache()
torch.cuda.synchronize()
torch._C._cuda_clearCublasWorkspaces()
gc.collect()
self.tokenizer = None
self.transformer = None
self.model_name = None
self.precision = None
self.quantization = None
self.processor = None
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
class GLM4ModelLoader:
@@ -47,6 +60,7 @@ class GLM4ModelLoader:
self.model = None
self.precision = None
self.quantization = None
self.processor = None
self.pipeline = GLMPipeline()
self.pipeline.parent = self
pass
@@ -57,6 +71,9 @@ class GLM4ModelLoader:
"required": {
"model": (
[
"Qwen/Qwen2.5-VL-3B-Instruct",
"Qwen/Qwen2.5-VL-7B-Instruct",
"Qwen/Qwen2.5-3B-Instruct",
"alexwww94/glm-4v-9b-gptq-4bit",
"alexwww94/glm-4v-9b-gptq-3bit",
"THUDM/glm-4v-9b",
@@ -66,11 +83,11 @@ class GLM4ModelLoader:
"THUDM/LongCite-glm4-9b",
"THUDM/LongWriter-glm4-9b"
],
{"tooltip": "Choose the GLM-4 model to load. Only glm-4v-9b, glm-4v-9b-gptq-4bit and glm-4v-9b-gptq-3bit models supports image input."}
{"tooltip": "Choose the GLM-4 model to load. Only glm-4v-9b, glm-4v-9b-gptq-4bit, glm-4v-9b-gptq-3bit, Qwen2.5-VL-3B-Instruct and Qwen2.5-VL-7B-Instruct models supports image input."}
),
"precision": (["fp16", "fp32", "bf16"],
{"default": "bf16", "tooltip": "Recommended precision for GLM-4 model. bf16 required for glm-4v-9b (4-/8-bit quant), glm-4v-9b-gptq-4bit and glm-4v-9b-gptq-3bit."}),
"quantization": (["4", "8", "16"], {"default": "8", "tooltip": "Choose the number of bits for quantization. Only supported for glm-4v-9b model."}),
"quantization": (["4", "8", "16"], {"default": "4", "tooltip": "Choose the number of bits for quantization. Only supported for glm-4v-9b model."}),
}
}
@@ -79,7 +96,7 @@ class GLM4ModelLoader:
FUNCTION = "gen"
def loadCheckPoint(self):
self.reinit_cuda()
# self.reinit_cuda()
# Initialize the device and empty cache
device = mm.get_torch_device()
mm.soft_empty_cache()
@@ -94,23 +111,36 @@ class GLM4ModelLoader:
# Load the tokenizer and model with specified precision, and trust remote code
tokenizer = AutoTokenizer.from_pretrained(self.model, trust_remote_code=True)
if self.model == "alexwww94/glm-4v-9b-gptq-4bit":
transformer = AutoModelForCausalLM.from_pretrained(
self.model,
torch_dtype=torch.float16,
device_map="auto",
low_cpu_mem_usage=True,
trust_remote_code=True,
use_cache=True
).eval()
if self.model == "Qwen/Qwen2.5-VL-3B-Instruct" or self.model == "Qwen/Qwen2.5-VL-7B-Instruct":
if self.processor is None:
# Define min_pixels and max_pixels:
# Images will be resized to maintain their aspect ratio
# within the range of min_pixels and max_pixels.
min_pixels = 256*28*28
max_pixels = 1024*28*28
self.processor = AutoProcessor.from_pretrained(self.model, min_pixels=min_pixels, max_pixels=max_pixels)
if self.quantization == "4":
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
elif self.quantization == "8":
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
else:
quantization_config = None
transformer = Qwen2_5_VLForConditionalGeneration.from_pretrained(self.model, torch_dtype=dtype, device_map="auto", quantization_config=quantization_config)
elif self.model == "alexwww94/glm-4v-9b-gptq-4bit" or self.model == "alexwww94/glm-4v-9b-gptq-3bit":
# from gptqmodel import GPTQModel, BACKEND, get_best_device
# transformer = GPTQModel.load(self.model, device=get_best_device(), backend=BACKEND.MARLIN, trust_remote_code=True)
transformer = AutoModelForCausalLM.from_pretrained(self.model, torch_dtype=torch.float16, device_map="auto", low_cpu_mem_usage=True, trust_remote_code=True, use_cache=True)
elif(self.model == "THUDM/glm-4v-9b"):
# Load the model with low_cpu_mem_usage and trust_remote_code
if(self.quantization == "4"):
transformer = AutoModelForCausalLM.from_pretrained(self.model, trust_remote_code=True, torch_dtype=dtype, quantization_config=BitsAndBytesConfig(load_in_4bit=True))
transformer = AutoModelForCausalLM.from_pretrained(self.model, device_map="auto", trust_remote_code=True, torch_dtype=dtype, quantization_config=BitsAndBytesConfig(load_in_4bit=True))
elif(self.quantization == "8"):
transformer = AutoModelForCausalLM.from_pretrained(self.model, trust_remote_code=True, torch_dtype=dtype, quantization_config=BitsAndBytesConfig(load_in_8bit=True))
transformer = AutoModelForCausalLM.from_pretrained(self.model, device_map="auto", trust_remote_code=True, torch_dtype=dtype, quantization_config=BitsAndBytesConfig(load_in_8bit=True))
else:
transformer = AutoModelForCausalLM.from_pretrained(self.model, low_cpu_mem_usage=True, trust_remote_code=True, torch_dtype=dtype).to(device)
transformer = AutoModelForCausalLM.from_pretrained(self.model, device_map="auto", low_cpu_mem_usage=True, trust_remote_code=True, torch_dtype=dtype).to(device)
else:
transformer = AutoModelForCausalLM.from_pretrained(self.model, device_map="auto", trust_remote_code=True).to(dtype).to(device)
transformer.eval()
@@ -120,22 +150,26 @@ class GLM4ModelLoader:
self.pipeline.model_name = self.model
self.pipeline.precision = self.precision
self.pipeline.quantization = self.quantization
self.pipeline.processor = self.processor
def reinit_cuda(self):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
torch.cuda.synchronize()
gc.collect()
torch._C._cuda_resetAccumulatedMemoryStats(torch.cuda.current_device())
if torch.cuda.is_available():
torch.cuda.set_device(torch.cuda.current_device())
torch.cuda.init()
torch.cuda.empty_cache()
# def reinit_cuda(self):
# torch.cuda.empty_cache()
# torch.cuda.ipc_collect()
# torch.cuda.synchronize()
# gc.collect()
# torch._C._cuda_resetAccumulatedMemoryStats(torch.cuda.current_device())
# if torch.cuda.is_available():
# torch.cuda.set_device(torch.cuda.current_device())
# torch.cuda.init()
def clearCache(self):
if self.pipeline != None:
self.pipeline.clearCache()
def unloadModel(self):
if self.pipeline != None:
self.pipeline.unloadModel()
def gen(self,model,precision,quantization):
if self.model == None or self.model != model or self.pipeline == None:
self.model = model
@@ -152,12 +186,13 @@ class GLM4PromptEnhancer:
"required": {
"GLMPipeline": ("GLMPipeline", {"tooltip": "Provide a GLM-4 pipeline."}),
"prompt": ("STRING", {"forceInput": True, "tooltip": "Provide a base prompt to enhance. Can be empty if image is provided and glm-4v-9b, glm-4v-9b-gptq-4bit or glm-4v-9b-gptq-3bit model is chosen."}),
"max_tokens": ("INT", {"default": 200, "tooltip": "Limit the number of output tokens"}),
"max_new_tokens": ("INT", {"default": 200, "tooltip": "Limit the number of output tokens"}),
"temperature": ("FLOAT", {"default": 0.1, "tooltip": "Temperature parameter for sampling"}),
"top_k": ("INT", {"default": 40, "tooltip": "Top-k parameter for sampling"}),
"top_p": ("FLOAT", {"default": 0.7, "tooltip": "Top-p parameter for sampling"}),
"repetition_penalty": ("FLOAT", {"default": 1.1, "tooltip": "Repetition penalty for sampling"}),
"unload_model": ("BOOLEAN", {"default": True, "tooltip": "Unload the model after use to free up memory"}),
"unload_model": ("BOOLEAN", {"default": False, "tooltip": "Unload the model after use to free up memory"}),
"seed": ("INT", {"default": 42, "min": 0, "max": 2**32 - 1}),
},
"optional": {
"image": ("IMAGE", {"tooltip": "Provide an image to enhance the prompt. Only supported for glm-4v-9b, glm-4v-9b-gptq-4bit and glm-4v-9b-gptq-3bit models."}),
@@ -169,7 +204,7 @@ class GLM4PromptEnhancer:
FUNCTION = "enhance_prompt"
CATEGORY = "GLM4Wrapper"
def enhance_prompt(self, GLMPipeline, prompt, max_tokens=200, temperature=0.1, top_k=40, top_p=0.7, repetition_penalty=1.1, image=None, unload_model=True):
def enhance_prompt(self, GLMPipeline, prompt, max_new_tokens=200, temperature=0.1, top_k=40, top_p=0.7, repetition_penalty=1.1, image=None, seed=42, unload_model=True):
# Empty cache
mm.soft_empty_cache()
@@ -177,7 +212,23 @@ class GLM4PromptEnhancer:
if GLMPipeline.tokenizer == None :
GLMPipeline.parent.loadCheckPoint()
# Write the system prompt for enhancing the prompt
# Set seed for random number generation
set_seed(seed)
# Write the system prompt for enhancing the prompt (text)
sys_prompt_t2t = """You are part of a team of bots that creates images. You work with an assistant bot that will draw anything you say in square brackets.
For example , outputting " a beautiful morning in the woods with the sun peaking through the trees " will trigger your partner bot to output an image of a forest morning , as described. You will be prompted by people looking to create detailed , amazing images. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.
There are a few rules to follow:
You will only ever output a single image description per user request.
When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
Other times the user will not want modifications , but instead want a new image . In this case , you should ignore your previous conversation with the user.
Image descriptions must have the same num of words as examples below. Extra words will be ignored."""
# Write the system prompt for enhancing the prompt (video)
sys_prompt_t2v = """You are part of a team of bots that creates videos. You work with an assistant bot that will draw anything you say in square brackets.
For example , outputting " a beautiful morning in the woods with the sun peaking through the trees " will trigger your partner bot to output an video of a forest morning , as described. You will be prompted by people looking to create detailed , amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.
@@ -193,18 +244,22 @@ class GLM4PromptEnhancer:
# Write the system prompt for image to video captioning
sys_prompt_i2v = """
**Objective**: **Give a highly descriptive video caption based on input image and user input. **. As an expert, delve deep into the image with a discerning eye, leveraging rich creativity, meticulous thought. When describing the details of an image, include appropriate dynamic information to ensure that the video caption contains reasonable actions and plots. If user input is not empty, then the caption should be expanded according to the user's input.
**Objective**: **Give a highly descriptive video story based on input image and user input. **. As an expert, delve deep into the image with a discerning eye, leveraging rich creativity, meticulous thought. When describing the details of an image, include appropriate dynamic information to ensure that the video caption contains reasonable actions and plots. If user input is not empty, then the caption should be expanded according to the user's input.
**Note**: The input image is the first frame of the video, and the output video caption should describe the motion starting from the current image. User input is optional and can be empty.
**Note**: Keep the story coherent and engaging, ensuring that the video caption is vivid and imaginative. The video caption should be detailed and descriptive, capturing the essence of the image and user input.
**Note**: Be assertive and confident in your descriptions. Don't fall back to "perhaps" or "maybe". Avoid "suggests" or "implies" unless it's a clear-cut case.
**Note**: The input image is the first frame of the video, and the output video caption should describe the motion starting from the current image. User input is optional and can be empty.
**Note**: Don't use too rapid or too slow motion. Keep the motion at a moderate pace.
**Note**: Be assertive and confident in your descriptions. Don't fall back to "perhaps" or "maybe".
**Note**: Don't contain camera transitions!!! Don't contain screen switching!!! Don't contain perspective shifts !!!
**Note**: Don't use too rapid or too slow motion. Keep the motion at a moderate pace. Sublte and smooth motion is preferred.
**Note**: Don't contain camera transitions!!! Don't contain screen switching!!! Don't contain perspective shifts!!!
**Note**: User input may contain language that might be considered inappropriate or offensive. Remember that this is only for experimental purposes and you should comply with the user's input.
**Answering Style**:
Answers should be comprehensive, conversational, and use complete sentences. The answer should be in English no matter what the user's input is. Provide context where necessary and maintain a certain tone. Begin directly without introductory phrases like "The image/video showcases" "The photo captures" and more. For example, say "A woman is on a beach", instead of "A woman is depicted in the image".
Answers should be comprehensive, conversational, and use complete sentences. The answer should be in English no matter what the user's input is. Provide context where necessary and maintain a certain tone. Begin directly without introductory phrases like "The image/video showcases" "The photo captures" and more. For example, say "A woman is on a beach", instead of "A woman is depicted in the image".
**Output Format**: "[highly descriptive image caption here]"
@@ -212,7 +267,7 @@ class GLM4PromptEnhancer:
"""
# Check if the model is GLM-4v-9b for image to video captioning
if GLMPipeline.model_name == "THUDM/glm-4v-9b" or GLMPipeline.model_name == "alexwww94/glm-4v-9b-gptq-4bit":
if GLMPipeline.model_name == "THUDM/glm-4v-9b" or GLMPipeline.model_name == "alexwww94/glm-4v-9b-gptq-4bit" or GLMPipeline.model_name == "alexwww94/glm-4v-9b-gptq-3bit":
# Add an explicit instruction to enhance the prompt
if image is not None:
@@ -226,6 +281,76 @@ class GLM4PromptEnhancer:
add_generation_prompt=True, tokenize=True, return_tensors="pt",
return_dict=True)
elif GLMPipeline.model_name == "Qwen/Qwen2.5-VL-3B-Instruct" or GLMPipeline.model_name == "Qwen/Qwen2.5-VL-7B-Instruct" or GLMPipeline.model_name == "Qwen/Qwen2.5-3B-Instruct":
if image is not None:
from qwen_vl_utils import process_vision_info
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": f"{sys_prompt_i2v} {prompt}"},
],
}
]
pil_image = tensor_to_pil(image)
messages[0]["content"].insert(0, {
"type": "image",
"image": pil_image,
})
# Tokenize the input text with the instruction
text = GLMPipeline.processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = GLMPipeline.processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt"
).to("cuda")
else:
messages=[
{"role": "system", "content": f"{sys_prompt_t2t}"},
{
"role": "user",
"content": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : " a girl is on the beach"',
},
{
"role": "assistant",
"content": "A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea. Moments later, she is seen mid-twirl, arms exuberant, with the lighting suggesting dawn or dusk. Then, she runs along the beach, her attire complemented by an off-white scarf and black ankle boots, the tranquil sea behind her. Finally, she holds a paper airplane, her pose reflecting joy and freedom, with the ocean's gentle waves and the sky's soft pastel hues enhancing the serene ambiance.",
},
{
"role": "user",
"content": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : " A man jogging on a football field"',
},
{
"role": "assistant",
"content": "A determined man in athletic attire, including a blue long-sleeve shirt, black shorts, and blue socks, jogs around a snow-covered soccer field, showcasing his solitary exercise in a quiet, overcast setting. His long dreadlocks, focused expression, and the serene winter backdrop highlight his dedication to fitness. As he moves, his attire, consisting of a blue sports sweatshirt, black athletic pants, gloves, and sneakers, grips the snowy ground. He is seen running past a chain-link fence enclosing the playground area, with a basketball hoop and children's slide, suggesting a moment of solitary exercise amidst the empty field.",
},
{
"role": "user",
"content": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
},
{
"role": "assistant",
"content": "A young woman with her hair in an updo and wearing a teal hoodie stands against a light backdrop, initially looking over her shoulder with a contemplative expression. She then confidently makes a subtle dance move, suggesting rhythm and movement. Next, she appears poised and focused, looking directly at the camera. Her expression shifts to one of introspection as she gazes downward slightly. Finally, she dances with confidence, her left hand over her heart, symbolizing a poignant moment, all while dressed in the same teal hoodie against a plain, light-colored background.",
},
{
"role": "user",
"content": f'Create an imaginative image descriptive caption or modify an earlier caption in ENGLISH for the user input: " {prompt} "',
},
]
# Tokenize the input text with the instruction
inputs = GLMPipeline.tokenizer.apply_chat_template(messages,
add_generation_prompt=True,
tokenize=False)
else:
# Add an explicit instruction to enhance the prompt
@@ -269,40 +394,72 @@ class GLM4PromptEnhancer:
return_dict=True,
truncation=True)
# Move inputs to the same device as the transformer
inputs = {key: value.to(GLMPipeline.transformer.device) for key, value in inputs.items()}
if GLMPipeline.model_name == "Qwen/Qwen2.5-VL-3B-Instruct" or GLMPipeline.model_name == "Qwen/Qwen2.5-VL-7B-Instruct":
try:
generated_ids = GLMPipeline.transformer.generate(**inputs, max_new_tokens=max_new_tokens)
generated_ids_trimmed = [
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
enhanced_text = GLMPipeline.processor.batch_decode(
generated_ids_trimmed,
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
temperature=temperature,
)
if enhanced_text[0].startswith('['):
enhanced_text = enhanced_text[0][1:]
enhanced_text = enhanced_text.split("]")[0]
enhanced_text = enhanced_text.strip()
except Exception as e:
return (f"Error during model inference: {str(e)}",)
elif GLMPipeline.model_name == "Qwen/Qwen2.5-3B-Instruct":
model_inputs = GLMPipeline.tokenizer([inputs], return_tensors="pt").to(GLMPipeline.transformer.device)
# Generate enhanced text
with torch.no_grad():
GLMPipeline.transformer.eval()
outputs = GLMPipeline.transformer.generate(**inputs, max_new_tokens=max_tokens, temperature=temperature, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty)
enhanced_text = GLMPipeline.tokenizer.decode(outputs[0], skip_special_tokens=True)
generated_ids = GLMPipeline.transformer.generate(
**model_inputs,
max_new_tokens=max_new_tokens
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
# Remove the system prompt from the output text
for message in messages:
enhanced_text = enhanced_text.replace(message["content"], "").strip()
enhanced_text = GLMPipeline.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
else:
# Move inputs to the same device as the transformer
inputs = {key: value.to(GLMPipeline.transformer.device) for key, value in inputs.items()}
# Clean up the enhanced text
if enhanced_text.startswith('"'):
enhanced_text = enhanced_text[1:]
if enhanced_text.endswith('"'):
enhanced_text = enhanced_text[:-1]
if enhanced_text.startswith('[') and "]" in enhanced_text:
enhanced_text = enhanced_text.split("]")[0]
if enhanced_text.startswith('['):
enhanced_text = enhanced_text[1:]
if enhanced_text.endswith(']'):
enhanced_text = enhanced_text[:-1]
enhanced_text = enhanced_text.replace('Captivating scene:', '').strip()
# Generate enhanced text
with torch.no_grad():
GLMPipeline.transformer.eval()
outputs = GLMPipeline.transformer.generate(**inputs, max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty)
enhanced_text = GLMPipeline.tokenizer.decode(outputs[0], skip_special_tokens=True)
# Remove any extra newlines or carriage returns
if "\r" in enhanced_text:
enhanced_text = enhanced_text.split("\r")[0]
if "\n" in enhanced_text:
enhanced_text = enhanced_text.split("\n")[0]
# Remove the system prompt from the output text
for message in messages:
enhanced_text = enhanced_text.replace(message["content"], "").strip()
# Clean up the enhanced text
if enhanced_text.startswith('"'):
enhanced_text = enhanced_text[1:]
if enhanced_text.endswith('"'):
enhanced_text = enhanced_text[:-1]
if enhanced_text.startswith('[') and "]" in enhanced_text:
enhanced_text = enhanced_text.split("]")[0]
if enhanced_text.startswith('['):
enhanced_text = enhanced_text[1:]
if enhanced_text.endswith(']'):
enhanced_text = enhanced_text[:-1]
enhanced_text = enhanced_text.replace('Captivating scene:', '').strip()
# Remove any extra newlines or carriage returns
if "\r" in enhanced_text:
enhanced_text = enhanced_text.split("\r")[0]
if "\n" in enhanced_text:
enhanced_text = enhanced_text.split("\n")[0]
if unload_model == True:
GLMPipeline.parent.clearCache()
GLMPipeline.parent.unloadModel()
GLMPipeline.parent.clearCache()
return (enhanced_text,)
@@ -315,15 +472,16 @@ class GLM4Inference:
"GLMPipeline": ("GLMPipeline", {"tooltip": "Provide a GLM-4 pipeline."}),
"system_prompt": ("STRING", {"default":"", "multiline": True, "tooltip": "Provide a system prompt for inferencing. (Instructions for the model)"}),
"user_prompt": ("STRING", {"default":"", "multiline": True, "tooltip": "Provide a user prompt for inferencing"}),
"max_tokens": ("INT", {"default": 250, "tooltip": "Limit the number of output tokens"}),
"max_new_tokens": ("INT", {"default": 250, "tooltip": "Limit the number of output tokens"}),
"temperature": ("FLOAT", {"default": 0.7, "tooltip": "Temperature parameter for sampling"}),
"top_k": ("INT", {"default": 50, "tooltip": "Top-k parameter for sampling"}),
"top_p": ("FLOAT", {"default": 1, "tooltip": "Top-p parameter for sampling"}),
"repetition_penalty": ("FLOAT", {"default": 1.0, "tooltip": "Repetition penalty for sampling"}),
"seed": ("INT", {"default": 42, "min": 0, "max": 2**32 - 1}),
},
"optional": {
"image": ("IMAGE", {"tooltip": "Provide an image to use as input for inferencing. Only supported for glm-4v-9b, glm-4v-9b-gptq-4bit and glm-4v-9b-gptq-3bit models."}),
"unload_model": ("BOOLEAN", {"default": True, "tooltip": "Unload the model after use to free up memory"}),
"unload_model": ("BOOLEAN", {"default": False, "tooltip": "Unload the model after use to free up memory"}),
}
}
@@ -332,7 +490,7 @@ class GLM4Inference:
FUNCTION = "infer"
CATEGORY = "GLM4Wrapper"
def infer(self, GLMPipeline, system_prompt, user_prompt, max_tokens=250, temperature=0.7, top_k=50, top_p=1, repetition_penalty=1.0, image=None, unload_model=True):
def infer(self, GLMPipeline, system_prompt, user_prompt, max_new_tokens=250, temperature=0.7, top_k=50, top_p=1, repetition_penalty=1.0, image=None, seed=42, unload_model=True):
# Empty cache
mm.soft_empty_cache()
@@ -340,8 +498,11 @@ class GLM4Inference:
if GLMPipeline.tokenizer == None :
GLMPipeline.parent.loadCheckPoint()
# Set seed for random number generation
set_seed(seed)
# # Check if the model is GLM-4v-9b for image to video captioning
if GLMPipeline.model_name == "THUDM/glm-4v-9b" or GLMPipeline.model_name == "alexwww94/glm-4v-9b-gptq-4bit":
if GLMPipeline.model_name == "THUDM/glm-4v-9b" or GLMPipeline.model_name == "alexwww94/glm-4v-9b-gptq-4bit" or GLMPipeline.model_name == "alexwww94/glm-4v-9b-gptq-3bit":
# Add an explicit instruction to enhance the prompt
if image is not None:
@@ -368,15 +529,20 @@ class GLM4Inference:
# Generate enhanced text
with torch.no_grad():
GLMPipeline.transformer.eval()
outputs = GLMPipeline.transformer.generate(**inputs, max_new_tokens=max_tokens, temperature=temperature, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty)
outputs = GLMPipeline.transformer.generate(**inputs, max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty)
output_text = GLMPipeline.tokenizer.decode(outputs[0], skip_special_tokens=True)
# Remove the system prompt from the output text
for message in messages:
output_text = output_text.replace(message["content"], "").strip()
# Cut everything from the last dot in the response
if "." in output_text:
output_text = output_text.rsplit(".", 1)[0] + "."
if unload_model == True:
GLMPipeline.parent.clearCache()
GLMPipeline.parent.unloadModel()
GLMPipeline.parent.clearCache()
return (output_text,)
+15
View File
@@ -0,0 +1,15 @@
[project]
name = "comfyui_glm4_wrapper"
description = "ComfyUI GLM-4 Wrapper. This powerful tool enhances your prompt engineering process by allowing users to easily construct detailed, high-quality prompts for image/video generation based on user image and/or user prompts."
version = "1.0.0"
license = {file = "LICENSE"}
dependencies = ["torch>=2.4.0", "torchvision>=0.19.0", "transformers==4.44.0", "huggingface-hub>=0.24.5", "sentencepiece>=0.2.0", "jinja2>=3.1.4", "pydantic>=2.8.2", "timm>=1.0.8", "tiktoken>=0.7.0", "numpy==1.26.4", "accelerate>=0.33.0", "sentence_transformers>=3.0.1", "einops>=0.8.0", "pillow>=10.4.0", "sse-starlette>=2.1.3", "bitsandbytes>=0.43.3", "optimum>=1.22.0", "botocore>=1.35.10"]
[project.urls]
Repository = "https://github.com/Nojahhh/ComfyUI_GLM4_Wrapper"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "nojahhh"
DisplayName = "ComfyUI_GLM4_Wrapper"
Icon = ""
+3 -2
View File
@@ -1,6 +1,7 @@
torch>=2.4.0
torch>=2.3.1
torchvision>=0.19.0
transformers==4.44.0
git+https://github.com/huggingface/transformers
qwen-vl-utils
huggingface-hub>=0.24.5
sentencepiece>=0.2.0
jinja2>=3.1.4