-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
365 lines (330 loc) · 12 KB
/
__init__.py
File metadata and controls
365 lines (330 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import os
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, AutoModel
from peft import PeftModel
import folder_paths
if not "huggingface" in folder_paths.folder_names_and_paths:
folder_paths.add_model_folder_path("huggingface", os.path.join(folder_paths.models_dir, "huggingface"))
class LoadHuggingFaceModel:
"""Node to load any HuggingFace model."""
CATEGORY = "transformers"
FUNCTION = "execute"
OUTPUT_NODE = False
RETURN_TYPES = ("hf_model", "hf_tokenizer")
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model_id": (
"STRING",
{
"default": "microsoft/Phi-3.5-mini-instruct",
"tooltip": "HuggingFace model ID or path"
}
),
"model_type": (
["auto", "causal_lm", "base"],
{
"default": "causal_lm",
"tooltip": "Type of model to load"
}
),
"device": (
["auto", "cuda", "cpu", "mps"],
{
"default": "auto",
"tooltip": "Device to load model on"
}
),
"torch_dtype": (
["auto", "float32", "float16", "bfloat16"],
{
"default": "auto",
"tooltip": "Data type for model weights"
}
),
},
"optional": {
"trust_remote_code": (
"BOOLEAN",
{
"default": False,
"tooltip": "Allow executing remote code from model repo"
}
),
"use_local_cache": (
"BOOLEAN",
{
"default": True,
"tooltip": "Use ComfyUI models folder for caching"
}
),
}
}
def execute(self, model_id, model_type, device, torch_dtype, trust_remote_code=False, use_local_cache=True):
# Handle torch dtype
dtype_map = {
"auto": "auto",
"float32": torch.float32,
"float16": torch.float16,
"bfloat16": torch.bfloat16
}
dtype = dtype_map[torch_dtype]
# Setup cache directory
cache_dir = None
if use_local_cache:
try:
hf_folder = folder_paths.get_folder_paths("huggingface")[0]
cache_dir = os.path.join(hf_folder, model_id.replace("/", "_"))
except:
pass
# Load model based on type
model_kwargs = {
"device_map": device,
"torch_dtype": dtype,
"trust_remote_code": trust_remote_code
}
if cache_dir:
model_kwargs["cache_dir"] = cache_dir
if model_type == "causal_lm":
model = AutoModelForCausalLM.from_pretrained(model_id, **model_kwargs)
elif model_type == "base":
model = AutoModel.from_pretrained(model_id, **model_kwargs)
else: # auto
try:
model = AutoModelForCausalLM.from_pretrained(model_id, **model_kwargs)
except:
model = AutoModel.from_pretrained(model_id, **model_kwargs)
# Load tokenizer
tokenizer_kwargs = {"trust_remote_code": trust_remote_code}
if cache_dir:
tokenizer_kwargs["cache_dir"] = cache_dir
tokenizer = AutoTokenizer.from_pretrained(model_id, **tokenizer_kwargs)
return (model, tokenizer)
class RunHuggingFaceModel:
"""Node to run inference with any HuggingFace model."""
CATEGORY = "transformers"
FUNCTION = "execute"
OUTPUT_NODE = False
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("output",)
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"hf_model": ("hf_model",),
"hf_tokenizer": ("hf_tokenizer",),
"task": (
["text-generation", "text2text-generation", "conversational"],
{
"default": "text-generation",
"tooltip": "HuggingFace pipeline task"
}
),
"prompt": (
"STRING",
{
"default": "What is the meaning of life?",
"multiline": True,
"tooltip": "Input prompt or instruction"
}
),
"max_new_tokens": (
"INT",
{
"default": 500,
"min": 1,
"max": 4096,
"tooltip": "Maximum tokens to generate"
}
),
"temperature": (
"FLOAT",
{
"default": 0.7,
"min": 0.01,
"max": 2.0,
"step": 0.01,
"tooltip": "Sampling temperature"
}
),
"do_sample": (
"BOOLEAN",
{
"default": True,
"tooltip": "Enable sampling (vs greedy decoding)"
}
),
"seed": (
"INT",
{
"default": 0,
"min": 0,
"max": 0xffffffffffffffff,
"tooltip": "Random seed for reproducibility"
}
),
},
"optional": {
"system_message": (
"STRING",
{
"default": "",
"multiline": True,
"tooltip": "Optional system message (for chat models)"
}
),
"return_full_text": (
"BOOLEAN",
{
"default": False,
"tooltip": "Return full text including prompt"
}
),
"top_p": (
"FLOAT",
{
"default": 1.0,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Nucleus sampling probability"
}
),
"top_k": (
"INT",
{
"default": 50,
"min": 0,
"max": 200,
"tooltip": "Top-k sampling parameter"
}
),
}
}
def execute(self, hf_model, hf_tokenizer, task, prompt, max_new_tokens, temperature,
do_sample, seed, system_message="", return_full_text=False, top_p=1.0, top_k=50):
# Set seed for reproducibility
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
# Build pipeline
pipe = pipeline(task, model=hf_model, tokenizer=hf_tokenizer)
# Prepare generation arguments
generation_args = {
"max_new_tokens": max_new_tokens,
"temperature": temperature,
"do_sample": do_sample,
"return_full_text": return_full_text,
"top_p": top_p,
"top_k": top_k,
}
# Handle different input formats based on task
if task in ["text-generation", "conversational"]:
# Check if model uses chat template
if hasattr(hf_tokenizer, 'chat_template') and hf_tokenizer.chat_template:
# Format as messages for chat models
messages = []
if system_message and system_message.strip():
messages.append({"role": "system", "content": system_message})
messages.append({"role": "user", "content": prompt})
output = pipe(messages, **generation_args)
else:
# Direct text input for non-chat models
if system_message and system_message.strip():
full_prompt = f"{system_message}\n\n{prompt}"
else:
full_prompt = prompt
output = pipe(full_prompt, **generation_args)
else:
# For other tasks, use direct text input
output = pipe(prompt, **generation_args)
# Extract text from output
if isinstance(output, list) and len(output) > 0:
result = output[0]
if isinstance(result, dict):
# For text-generation tasks
if "generated_text" in result:
response = result["generated_text"]
# If it's a list of messages, extract the assistant's response
if isinstance(response, list):
for msg in reversed(response):
if msg.get("role") == "assistant":
response = msg.get("content", "")
break
else:
response = str(response)
else:
response = str(result)
else:
response = str(result)
else:
response = str(output)
return (response,)
class ApplyLoRAAdapter:
"""Node to apply a LoRA adapter to a loaded HuggingFace model."""
CATEGORY = "transformers"
FUNCTION = "execute"
OUTPUT_NODE = False
RETURN_TYPES = ("hf_model",)
RETURN_NAMES = ("hf_model",)
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"hf_model": ("hf_model",),
"lora_model_id": (
"STRING",
{
"default": "",
"tooltip": "HuggingFace LoRA adapter ID or local path"
}
),
},
"optional": {
"trust_remote_code": (
"BOOLEAN",
{
"default": False,
"tooltip": "Allow executing remote code from adapter repo"
}
),
"use_local_cache": (
"BOOLEAN",
{
"default": True,
"tooltip": "Use ComfyUI models folder for caching"
}
),
}
}
def execute(self, hf_model, lora_model_id, trust_remote_code=False, use_local_cache=True):
cache_dir = None
if use_local_cache:
try:
hf_folder = folder_paths.get_folder_paths("huggingface")[0]
cache_dir = os.path.join(hf_folder, lora_model_id.replace("/", "_"))
except:
pass
kwargs = {"trust_remote_code": trust_remote_code}
if cache_dir:
kwargs["cache_dir"] = cache_dir
model = PeftModel.from_pretrained(hf_model, lora_model_id, **kwargs)
return (model,)
# Register nodes
NODE_CLASS_MAPPINGS = {
"LoadHuggingFaceModel": LoadHuggingFaceModel,
"RunHuggingFaceModel": RunHuggingFaceModel,
"ApplyLoRAAdapter": ApplyLoRAAdapter,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"LoadHuggingFaceModel": "Load HuggingFace Model",
"RunHuggingFaceModel": "Run HuggingFace Model",
"ApplyLoRAAdapter": "Apply LoRA Adapter",
}