-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.py
More file actions
1203 lines (1056 loc) · 46.3 KB
/
Copy pathnodes.py
File metadata and controls
1203 lines (1056 loc) · 46.3 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
ComfyUI Remote Text Encoder – Node implementations
===================================================
Node graph (mirrors the built-in SD / SDXL / LTX-Video workflow):
┌─────────────────────┐
│ RemoteCLIPLoader │ server_url, model_name, api_key
└────────┬────────────┘
│ REMOTE_CLIP
▼
┌──────────────────────────┐
│ CLIPTextEncodeRemote │ text, clip_skip, max_length
└────────┬─────────────────┘
│ CONDITIONING
▼
KSampler / etc.
For SDXL (dual encoder):
RemoteDualCLIPLoader ──► CLIPTextEncodeCoupleRemote ──► CONDITIONING
(model 1 = clip-l, model 2 = clip-g)
For LTX-Video 2.3 (T5-XXL + Gemma-3-12B):
RemoteDualCLIPLoader ──► LTXVTextEncodeRemote ──► CONDITIONING
(model 1 = T5-XXL, model 2 = Gemma-3-12B)
"""
from __future__ import annotations
import base64
import logging
from dataclasses import dataclass
from typing import Any, Optional
import numpy as np
import requests
import torch
import torch.nn as nn
import folder_paths
from safetensors.torch import load_file as _safetensors_load_file
from . import server_config
from .server_config import (
MODEL_PLACEHOLDER,
refresh_models,
_cached_models_map,
)
logger = logging.getLogger("comfyui.remote_text_encoder")
# ── Path helpers ──────────────────────────────────────────────────────────────
def _find_ltxv_projection() -> str:
"""
Search ComfyUI's ``text_encoders`` folder(s) for an LTX-V 2.x projection
safetensors file and return the first match found.
Matches filenames that contain both ``projection`` and
``ltx`` (case-insensitive), e.g.:
• ltx-2.3_text_projection_bf16.safetensors
• ltxv_text_projection_fp16.safetensors
Falls back to an empty string if nothing is found or if ``folder_paths``
is not importable (i.e. running outside ComfyUI).
"""
try:
import folder_paths # only available inside a ComfyUI process
search_dirs = folder_paths.get_folder_paths("text_encoders")
except Exception:
return ""
import glob
import os
for d in search_dirs:
for path in sorted(glob.glob(os.path.join(d, "*.safetensors"))):
name_lower = os.path.basename(path).lower()
if "projection" in name_lower and "ltx" in name_lower:
return path
return ""
# ── Types ─────────────────────────────────────────────────────────────────────
# Keep as an internal alias so old serialised workflows that reference the
# string don't break, but loaders now advertise the standard "CLIP" socket.
REMOTE_CLIP_TYPE = "CLIP"
# ── Connection handle ─────────────────────────────────────────────────────────
@dataclass
class RemoteCLIPConnection:
"""Holds everything needed to call the Remote Text Encoder server."""
server_url: str # e.g. "http://192.168.1.10:8288"
model_name: str # HF repo-id or local path on the server
api_key: Optional[str] # Bearer token, or None
clip_skip: int # Passed as a hint; the server-side skip is 1-based
timeout: int # HTTP request timeout in seconds
@property
def _headers(self) -> dict:
h = {"Content-Type": "application/json"}
if self.api_key:
h["Authorization"] = f"Bearer {self.api_key}"
return h
def encode(
self,
text: str,
*,
max_length: int = 77,
return_pooled: bool = True,
) -> dict[str, Any]:
"""
Call POST /comfy/encode and return the raw response dict.
Raises requests.HTTPError on server-side failures.
"""
url = self.server_url.rstrip("/") + "/comfy/encode"
payload = {
"model_name": self.model_name,
"text": text,
"clip_skip": self.clip_skip,
}
resp = requests.post(url, json=payload, headers=self._headers, timeout=self.timeout)
resp.raise_for_status()
return resp.json()
def encode_batch(
self,
texts: list[str],
*,
max_length: int = 77,
return_pooled: bool = True,
) -> dict[str, Any]:
"""
Call POST /encode for a batch of texts.
Returns {"embeddings_b64": ..., "pooled_b64": ..., "shape": [...]}
"""
url = self.server_url.rstrip("/") + "/encode"
payload = {
"model": self.model_name,
"texts": texts,
"max_length": max_length,
"return_pooled": return_pooled,
}
resp = requests.post(url, json=payload, headers=self._headers, timeout=self.timeout)
resp.raise_for_status()
return resp.json()
def encode_ltxv(
self,
gemma_model_name: str,
text: str,
*,
t5_max_length: int = 256,
gemma_max_length: int = 512,
) -> dict[str, Any]:
"""
Call POST /comfy/encode/ltxv – encodes with T5 (self.model_name) and
Gemma (gemma_model_name) in one round-trip. Both models must be loaded
on the same server instance.
"""
url = self.server_url.rstrip("/") + "/comfy/encode/ltxv"
payload = {
"t5_model": self.model_name,
"gemma_model": gemma_model_name,
"text": text,
"t5_max_length": t5_max_length,
"gemma_max_length": gemma_max_length,
}
resp = requests.post(url, json=payload, headers=self._headers, timeout=self.timeout)
resp.raise_for_status()
return resp.json()
def tokenize(self, text: str) -> dict:
"""
ComfyUI CLIP duck-type interface.
Stores the text so encode_from_tokens can forward it to the server.
"""
return {"text": text}
def encode_from_tokens(
self,
tokens: dict,
return_pooled: bool = True,
return_dict: bool = False,
):
"""
ComfyUI CLIP duck-type interface.
Calls the server and returns (cond [1,T,D], pooled [1,D]) so this
object can be wired directly into any standard ComfyUI encode node.
"""
data = self.encode(tokens["text"], return_pooled=return_pooled)
cond = _b64_to_tensor(data["cond"][0], data["shape"]).unsqueeze(0)
if return_pooled:
pooled = _b64_to_tensor(
data["cond"][1]["pooled_output"], data["pooled_shape"]
).unsqueeze(0)
return cond, pooled
return cond
def ping(self) -> bool:
"""Quick health-check – returns True if the server responds."""
try:
r = requests.get(self.server_url.rstrip("/") + "/", timeout=5, headers=self._headers)
return r.status_code == 200
except Exception:
return False
@property
def cond_stage_model(self):
raise RuntimeError(
"RemoteCLIPConnection cannot be used with LoRA loaders. "
"LoRA patching modifies local model weights and is incompatible with a "
"remote CLIP connection. Apply LoRAs on the server side, or use a local "
"CLIP model for LoRA loading before feeding into a Remote encode node."
)
@dataclass
class RemoteDualCLIPConnection:
"""
Dual-encoder CLIP object. Mirrors what ComfyUI's DualCLIPLoader produces:
two models loaded internally, one CLIP socket out.
Implements the ComfyUI CLIP duck-type (tokenize / encode_from_tokens) so it
can be dropped into any standard encode node. Our custom nodes
(CLIPTextEncodeCoupleRemote, LTXVTextEncodeRemote) cast it back to this
type when they need to call the two encoders separately.
"""
clip1: RemoteCLIPConnection # CLIP-L (SDXL) or T5-XXL (LTX-V)
clip2: RemoteCLIPConnection # CLIP-G (SDXL) or Gemma-3-12B (LTX-V)
def tokenize(self, text: str) -> dict:
return {"text": text}
def encode_from_tokens(
self,
tokens: dict,
return_pooled: bool = True,
return_dict: bool = False,
):
"""
Default encode: SDXL-style dual encode with the same text for both
encoders. Suitable for standard CLIPTextEncode nodes.
"""
text = tokens["text"]
data_l = self.clip1.encode(text, return_pooled=False)
data_g = self.clip2.encode(text, return_pooled=True)
emb_l = _b64_to_tensor(data_l["cond"][0], data_l["shape"])
emb_g = _b64_to_tensor(data_g["cond"][0], data_g["shape"])
t_l, t_g = emb_l.shape[0], emb_g.shape[0]
if t_l < t_g:
emb_l = torch.cat([emb_l, torch.zeros(t_g - t_l, emb_l.shape[1])], dim=0)
elif t_g < t_l:
emb_g = torch.cat([emb_g, torch.zeros(t_l - t_g, emb_g.shape[1])], dim=0)
cond = torch.cat([emb_l, emb_g], dim=-1).unsqueeze(0)
pooled = _b64_to_tensor(
data_g["cond"][1]["pooled_output"], data_g["pooled_shape"]
).unsqueeze(0)
if return_pooled:
return cond, pooled
return cond
@property
def cond_stage_model(self):
raise RuntimeError(
"RemoteDualCLIPConnection cannot be used with LoRA loaders. "
"LoRA patching modifies local model weights and is incompatible with a "
"remote CLIP connection. Apply LoRAs on the server side, or use a local "
"CLIP model for LoRA loading before feeding into a Remote encode node."
)
class _DualLinearProjection(nn.Module):
"""
Local replica of ComfyUI's ``DualLinearProjection`` (lt.py).
Takes the raw all-hidden tensor [B, L, T, D] and returns
[B, T, out_video + out_audio] (e.g. [B, T, 6144] for the 2.3 release).
"""
def __init__(self, in_dim: int, out_dim_video: int, out_dim_audio: int):
super().__init__()
self.video_aggregate_embed = nn.Linear(in_dim, out_dim_video, bias=True)
self.audio_aggregate_embed = nn.Linear(in_dim, out_dim_audio, bias=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
import math
source_dim = x.shape[-1] # D (= 3840)
x = x.movedim(1, -1) # [B, T, D, L]
# RMS-normalise over the D dimension, then flatten D×L
x = (x * torch.rsqrt(torch.mean(x ** 2, dim=2, keepdim=True) + 1e-6)
).flatten(start_dim=2) # [B, T, D*L]
video = self.video_aggregate_embed(
x * math.sqrt(self.video_aggregate_embed.out_features / source_dim)
)
audio = self.audio_aggregate_embed(
x * math.sqrt(self.audio_aggregate_embed.out_features / source_dim)
)
return torch.cat((video, audio), dim=-1)
@dataclass
class LTXVRemoteCLIPConnection:
"""
Hybrid encoder for LTX-Video 2.x (Gemma-3-12B on server + local projection).
Gemma runs remotely on the GPU server and returns ALL hidden states
(embedding layer + 48 transformer layers = 49 total, shape [1, 49, T, 3840]).
The projection module (loaded from a local ``.safetensors`` file) is applied
here. Two projection types are supported:
``single_linear``
``Linear(3840×49 → 3840, bias=False)``
Key: ``text_embedding_projection.weight``
Output: [B, T, 3840]
``dual_linear``
``DualLinearProjection(3840×49 → video_dim + audio_dim)``
Keys: ``text_embedding_projection.video_aggregate_embed.*``
``text_embedding_projection.audio_aggregate_embed.*``
Output: [B, T, video_dim + audio_dim] (e.g. [B, T, 6144])
"""
server_url: str
model_name: str
api_key: Optional[str]
timeout: int
gemma_max_length: int
projection: nn.Module # single_linear → nn.Linear | dual_linear → _DualLinearProjection
projection_type: str # "single_linear" or "dual_linear"
@property
def _headers(self) -> dict:
h = {"Content-Type": "application/json"}
if self.api_key:
h["Authorization"] = f"Bearer {self.api_key}"
return h
def tokenize(self, text: str) -> dict:
return {"text": text}
def encode_ltxv(self, text: str) -> tuple:
"""
Encode *text* via the server then apply the local projection.
Returns
-------
cond : torch.Tensor [1, T, 3840] float32
pooled : torch.Tensor [1, 3840] float32
extra : {"unprocessed_ltxav_embeds": True} – consumed by av_model.py
"""
url = self.server_url.rstrip("/") + "/comfy/encode/gemma_raw"
payload = {
"model_name": self.model_name,
"text": text,
"max_length": self.gemma_max_length,
}
resp = requests.post(url, json=payload, headers=self._headers, timeout=self.timeout)
resp.raise_for_status()
data = resp.json()
# ── Decode all-hidden tensor [1, L, T, D] ───────────────────────────
# Server sends bfloat16 bytes viewed as int16 (numpy has no bf16 dtype).
# Reverse: read as int16, reinterpret as bfloat16 via torch view, cast to float32.
shape = data["all_hidden_shape"]
raw = base64.b64decode(data["all_hidden_b64"])
wire_dtype = data.get("dtype", "float16")
if wire_dtype == "bfloat16":
all_hidden = torch.from_numpy(
np.frombuffer(raw, dtype=np.int16).reshape(shape).copy()
).view(torch.bfloat16).float() # [B, L, T, D]
else:
all_hidden = torch.from_numpy(
np.frombuffer(raw, dtype=np.float16).reshape(shape).copy()
).float() # [B, L, T, D] – legacy float16 path
# ── Decode pooled [D] ────────────────────────────────────────────────
p_raw = base64.b64decode(data["pooled_b64"])
p_shape = data["pooled_shape"]
pooled = torch.from_numpy(
np.frombuffer(p_raw, dtype=np.float32).reshape(p_shape).copy()
).unsqueeze(0) # [1, D]
# ── Apply projection (mirrors lt.py LTXAVTEModel.encode_token_weights) ─
proj_device = next(self.projection.parameters()).device
out = all_hidden.to(proj_device) # [B, L, T, D]
if self.projection_type == "single_linear":
# movedim(1,-1) → [B, T, D, L]
# range-normalise to [-8, 8] over dims (T, D)
# reshape → [B, T, D*L] = [B, T, 3840*49]
# Linear(188160 → 3840)
out = out.movedim(1, -1) # [B, T, D, L]
mean = out.mean(dim=(1, 2), keepdim=True)
rng = out.amax(dim=(1, 2), keepdim=True) - out.amin(dim=(1, 2), keepdim=True)
out = 8.0 * (out - mean) / (rng + 1e-6)
out = out.reshape(out.shape[0], out.shape[1], -1) # [B, T, D*L]
out = self.projection(out) # [B, T, 3840]
else:
# dual_linear: DualLinearProjection does its own movedim + RMS norm
# input: [B, L, T, D] → output: [B, T, video_dim + audio_dim]
out = self.projection(out)
out = out.float().cpu() # ensure float32 on CPU
return out, pooled, {"unprocessed_ltxav_embeds": True}
@property
def cond_stage_model(self):
raise RuntimeError(
"LTXVRemoteCLIPConnection cannot be used with LoRA loaders. "
"The projection weights are loaded locally, but LoRA patching requires "
"the full model graph. Apply LoRAs on the server side instead."
)
# ── Decode helpers ────────────────────────────────────────────────────────────
def _b64_to_tensor(b64: str, shape: list[int]) -> torch.Tensor:
"""Decode base64 raw float32 bytes → torch.Tensor on CPU."""
raw = base64.b64decode(b64)
arr = np.frombuffer(raw, dtype=np.float32).reshape(shape).copy()
return torch.from_numpy(arr)
def _comfy_encode_response_to_conditioning(
data: dict[str, Any],
) -> list[tuple[torch.Tensor, dict]]:
"""
Convert a /comfy/encode response into ComfyUI CONDITIONING format:
[[cond_tensor [T, D], {"pooled_output": pooled_tensor [D]}]]
"""
emb = _b64_to_tensor(data["cond"][0], data["shape"]) # [T, D]
pooled = _b64_to_tensor(
data["cond"][1]["pooled_output"], data["pooled_shape"]
) # [D]
# ComfyUI expects cond as [1, T, D]
cond = emb.unsqueeze(0)
return [[cond, {"pooled_output": pooled.unsqueeze(0)}]]
def _batch_encode_to_conditioning(
data: dict[str, Any],
) -> list[tuple[torch.Tensor, dict]]:
"""
Convert a /encode batch response (single text item) into
ComfyUI CONDITIONING format.
"""
shape: list[int] = data["shape"] # [B, T, D]
emb = _b64_to_tensor(data["embeddings_b64"], shape) # [B, T, D]
result = []
for i in range(shape[0]):
extra: dict[str, Any] = {}
if data.get("pooled_b64"):
pooled_shape = [shape[0], shape[2]]
pooled_full = _b64_to_tensor(data["pooled_b64"], pooled_shape)
extra["pooled_output"] = pooled_full[i].unsqueeze(0) # [1, D]
result.append([emb[i].unsqueeze(0), extra]) # [1, T, D]
return result
# ── Node: RemoteCLIPLoader ────────────────────────────────────────────────────
class RemoteCLIPLoader:
"""
Replacement for the built-in CLIPLoader / DualCLIPLoader nodes.
The ``model_name`` dropdown is populated live from the server’s
GET /v1/models endpoint using the URL stored in ``rte_config.json``.
Run the **Refresh Remote Models** utility node or press F5 in ComfyUI
to update the list after loading a new model on the server.
If a model you need is not in the dropdown yet, type its name into
the ``custom_model`` field – this overrides the dropdown selection.
Outputs a REMOTE_CLIP handle that stores the server connection
parameters. No network call is made at load time.
"""
CATEGORY = "conditioning/remote"
RETURN_TYPES = ("CLIP",)
RETURN_NAMES = ("clip",)
FUNCTION = "load"
@classmethod
def INPUT_TYPES(cls):
models_map = refresh_models(server_config._cache_server_url)
model_names = list(models_map.keys())
return {
"required": {
"server_url": (
"STRING",
{
"default": "http://localhost:8288",
"multiline": False,
"tooltip": "Base URL of the Remote Text Encoder server. "
"Changing this and pressing F5 refreshes the model list.",
},
),
"model_name": (
model_names,
{
"tooltip": "Select a model discovered from the server via GET /v1/models. "
"Use 'custom_model' to enter a name not in this list.",
},
),
"clip_skip": (
"INT",
{
"default": 1,
"min": 1,
"max": 12,
"step": 1,
"tooltip": "Number of CLIP layers to skip (1 = no skip).",
},
),
"timeout": (
"INT",
{
"default": 60,
"min": 5,
"max": 600,
"step": 5,
"tooltip": "HTTP request timeout in seconds.",
},
),
},
"optional": {
"api_key": (
"STRING",
{
"default": "",
"multiline": False,
"tooltip": "Bearer API key if the server requires authentication.",
},
),
"custom_model": (
"STRING",
{
"default": "",
"multiline": False,
"tooltip": "If non-empty, overrides the model_name dropdown. "
"Use this for models not yet in the discovery list.",
},
),
},
}
def load(
self,
server_url: str,
model_name: str,
clip_skip: int,
timeout: int,
api_key: str = "",
custom_model: str = "",
) -> tuple[RemoteCLIPConnection]:
actual_model = custom_model.strip() if custom_model.strip() else model_name
if actual_model == MODEL_PLACEHOLDER:
raise ValueError(
"No model selected. Either pick one from the dropdown or enter a name in 'custom_model'."
)
# Resolve short display name → full path (if we have a cached map)
if not custom_model.strip():
from .server_config import _cached_models_map
if actual_model in _cached_models_map and _cached_models_map[actual_model]:
actual_model = _cached_models_map[actual_model]
# Remember the URL so the next R-refresh queries the right server
refresh_models(server_url.strip(), api_key.strip(), timeout)
conn = RemoteCLIPConnection(
server_url=server_url.strip(),
model_name=actual_model,
api_key=api_key.strip() or None,
clip_skip=clip_skip,
timeout=timeout,
)
logger.info(
"RemoteCLIPLoader: server=%s model=%s clip_skip=%d",
conn.server_url,
conn.model_name,
conn.clip_skip,
)
return (conn,)
# ── Node: RemoteDualCLIPLoader ──────────────────────────────────────────────
class RemoteDualCLIPLoader:
"""
Loads two text encoders from the same server and outputs a single CLIP
object — exactly like ComfyUI's built-in DualCLIPLoader.
Wire the output to:
• CLIPTextEncodeRemote – encodes the same text with both models (SDXL default)
• CLIPTextEncodeCoupleRemote – SDXL with separate text_l / text_g prompts
• LTXVTextEncodeRemote – LTX-Video T5 + Gemma encoding
• Any standard ComfyUI CLIPTextEncode node
"""
CATEGORY = "conditioning/remote"
RETURN_TYPES = ("CLIP",)
RETURN_NAMES = ("clip",)
FUNCTION = "load"
@classmethod
def INPUT_TYPES(cls):
models_map = refresh_models(server_config._cache_server_url or "http://localhost:8288")
model_names = list(models_map.keys())
return {
"required": {
"server_url": (
"STRING",
{
"default": "http://localhost:8288",
"multiline": False,
"tooltip": "Base URL of the Remote Text Encoder server.",
},
),
"model_name_1": (
model_names,
{"tooltip": "First encoder (e.g. CLIP-L for SDXL, T5-XXL for LTX-Video)."},
),
"model_name_2": (
model_names,
{"tooltip": "Second encoder (e.g. CLIP-G for SDXL, Gemma-3-12B for LTX-Video)."},
),
"clip_skip": (
"INT",
{"default": 1, "min": 1, "max": 12, "step": 1,
"tooltip": "CLIP layer skip applied to both encoders."},
),
"timeout": (
"INT",
{"default": 60, "min": 5, "max": 600, "step": 5,
"tooltip": "HTTP request timeout in seconds."},
),
},
"optional": {
"api_key": (
"STRING",
{"default": "", "multiline": False,
"tooltip": "Bearer API key if the server requires authentication."},
),
},
}
def load(
self,
server_url: str,
model_name_1: str,
model_name_2: str,
clip_skip: int,
timeout: int,
api_key: str = "",
) -> tuple[RemoteDualCLIPConnection]:
url = server_url.strip()
key = api_key.strip() or None
models_map = refresh_models(url, api_key.strip(), timeout)
def _resolve(name: str) -> str:
return models_map.get(name, name) or name
conn1 = RemoteCLIPConnection(
server_url=url, model_name=_resolve(model_name_1),
api_key=key, clip_skip=clip_skip, timeout=timeout,
)
conn2 = RemoteCLIPConnection(
server_url=url, model_name=_resolve(model_name_2),
api_key=key, clip_skip=clip_skip, timeout=timeout,
)
logger.info(
"RemoteDualCLIPLoader: server=%s model_1=%s model_2=%s",
url, conn1.model_name, conn2.model_name,
)
return (RemoteDualCLIPConnection(clip1=conn1, clip2=conn2),)
# ── Node: LTXVRemoteCLIPLoader ────────────────────────────────────────────────
class LTXVRemoteCLIPLoader:
"""
LTX-Video 2.3 hybrid CLIP loader: Gemma-3-12B runs on the remote server,
the ``text_embedding_projection`` linear layer loads from a local
``.safetensors`` file and runs on the ComfyUI machine.
Why split? Gemma-3-12B is ~12 GB – offload it to a server with a big GPU.
The projection weights (``ltx-2.3_text_projection_bf16.safetensors``) are
~1.4 GB; keeping them local avoids syncing large files to the server while
still saving the dominant VRAM cost.
Required projection .safetensors keys
--------------------------------------
• ``text_embedding_projection.weight`` shape [3840, 188160] (= 3840 × 3840 × 49)
Connect:
LTXVRemoteCLIPLoader.clip → LTXVTextEncodeRemote.clip
"""
CATEGORY = "conditioning/remote"
RETURN_TYPES = ("CLIP",)
RETURN_NAMES = ("clip",)
FUNCTION = "load"
@classmethod
def INPUT_TYPES(cls):
models_map = refresh_models(server_config._cache_server_url or "http://localhost:8288")
model_names = list(models_map.keys())
return {
"required": {
"server_url": (
"STRING",
{
"default": "http://localhost:8288",
"multiline": False,
"tooltip": "Base URL of the Remote Text Encoder server.",
},
),
"model_name": (
model_names,
{
"tooltip": "Gemma-3-12B model on the server "
"(HF repo-id or path to .safetensors).",
},
),
"projection_path": (
folder_paths.get_filename_list("text_encoders"),
{
"tooltip": "Projection file from the text_encoders folder "
"(e.g. ltx-2.3_text_projection_bf16.safetensors).",
},
),
"gemma_max_length": (
"INT",
{
"default": 1024,
"min": 64,
"max": 8192,
"step": 64,
"tooltip": "Max Gemma token length. "
"LTX-V 2.3 tokenizer pads prompts to at least 1024 tokens.",
},
),
"timeout": (
"INT",
{
"default": 120,
"min": 5,
"max": 600,
"step": 5,
"tooltip": "HTTP request timeout in seconds "
"(all-layer Gemma encode may be slower than single-layer).",
},
),
},
"optional": {
"api_key": (
"STRING",
{
"default": "",
"multiline": False,
"tooltip": "Bearer API key if the server requires authentication.",
},
),
"custom_model": (
"STRING",
{
"default": "",
"multiline": False,
"tooltip": "Overrides the model_name dropdown. "
"Use for models not yet in the discovery list.",
},
),
},
}
def load(
self,
server_url: str,
model_name: str,
projection_path: str,
gemma_max_length: int,
timeout: int,
api_key: str = "",
custom_model: str = "",
) -> tuple:
# ── Resolve model name ────────────────────────────────────────────────
actual_model = custom_model.strip() if custom_model.strip() else model_name
if actual_model == MODEL_PLACEHOLDER:
raise ValueError(
"No Gemma model selected. Either pick from the dropdown or use 'custom_model'."
)
if not custom_model.strip():
from .server_config import _cached_models_map
if actual_model in _cached_models_map and _cached_models_map[actual_model]:
actual_model = _cached_models_map[actual_model]
refresh_models(server_url.strip(), api_key.strip(), timeout)
# ── Load local projection weights ─────────────────────────────────────
proj_path = folder_paths.get_full_path_or_raise("text_encoders", projection_path)
logger.info("LTXVRemoteCLIPLoader: loading projection from %s", proj_path)
sd = _safetensors_load_file(proj_path)
logger.info("LTXVRemoteCLIPLoader: keys in file: %s",
{k: tuple(v.shape) for k, v in sd.items()})
# ── Detect projection type from state-dict keys ───────────────────────
has_weight = "text_embedding_projection.weight" in sd
has_video = "text_embedding_projection.video_aggregate_embed.weight" in sd
has_audio = "text_embedding_projection.audio_aggregate_embed.weight" in sd
has_legacy = "text_projection" in sd
if has_video and has_audio:
# ── dual_linear ─────────────────────────────────────────────────
proj_type = "dual_linear"
vid_w = sd["text_embedding_projection.video_aggregate_embed.weight"].float()
vid_b = sd.get("text_embedding_projection.video_aggregate_embed.bias")
aud_w = sd["text_embedding_projection.audio_aggregate_embed.weight"].float()
aud_b = sd.get("text_embedding_projection.audio_aggregate_embed.bias")
in_f = vid_w.shape[1]
out_video = vid_w.shape[0]
out_audio = aud_w.shape[0]
projection = _DualLinearProjection(in_f, out_video, out_audio)
projection.video_aggregate_embed.weight = nn.Parameter(vid_w)
if vid_b is not None:
projection.video_aggregate_embed.bias = nn.Parameter(vid_b.float())
projection.audio_aggregate_embed.weight = nn.Parameter(aud_w)
if aud_b is not None:
projection.audio_aggregate_embed.bias = nn.Parameter(aud_b.float())
logger.info(
"LTXVRemoteCLIPLoader: dual_linear projection in=%d video_out=%d audio_out=%d",
in_f, out_video, out_audio,
)
elif has_weight or has_legacy:
# ── single_linear ────────────────────────────────────────────────
proj_type = "single_linear"
proj_weight = (sd["text_embedding_projection.weight"] if has_weight
else sd["text_projection"]).float()
# Some checkpoints pack it flat; reshape if needed
if proj_weight.ndim == 1:
out_f = 3840
if proj_weight.numel() % out_f != 0:
raise ValueError(
f"Cannot reshape 1-D projection tensor of size "
f"{proj_weight.numel()} into [3840, N]"
)
proj_weight = proj_weight.reshape(out_f, -1)
out_f, in_f = proj_weight.shape
projection = nn.Linear(in_f, out_f, bias=False)
projection.weight = nn.Parameter(proj_weight)
logger.info(
"LTXVRemoteCLIPLoader: single_linear projection in=%d out=%d",
in_f, out_f,
)
else:
raise ValueError(
f"Cannot determine projection type from keys: {list(sd.keys())}. "
"Expected 'text_embedding_projection.weight' (single_linear) or "
"'text_embedding_projection.video_aggregate_embed.weight' (dual_linear)."
)
projection.eval()
conn = LTXVRemoteCLIPConnection(
server_url=server_url.strip(),
model_name=actual_model,
api_key=api_key.strip() or None,
timeout=timeout,
gemma_max_length=gemma_max_length,
projection=projection,
projection_type=proj_type,
)
logger.info(
"LTXVRemoteCLIPLoader: server=%s model=%s projection_type=%s",
conn.server_url, conn.model_name, proj_type,
)
return (conn,)
# ── Node: CLIPTextEncodeRemote ────────────────────────────────────────────────
class CLIPTextEncodeRemote:
"""
Drop-in replacement for CLIPTextEncode that sends the prompt to the
Remote Text Encoder server and returns standard ComfyUI CONDITIONING.
Connect:
RemoteCLIPLoader.clip → CLIPTextEncodeRemote.clip
primitive string → CLIPTextEncodeRemote.text
CONDITIONING output → KSampler.positive / .negative
"""
CATEGORY = "conditioning/remote"
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"clip": ("CLIP", {}),
"text": (
"STRING",
{
"default": "",
"multiline": True,
"dynamicPrompts": True,
"tooltip": "The text prompt to encode.",
},
),
},
"optional": {
"max_length": (
"INT",
{
"default": 77,
"min": 16,
"max": 4096,
"step": 1,
"tooltip": "Maximum token length (must match the model's limit).",
},
),
},
}
def encode(
self,
clip: RemoteCLIPConnection,
text: str,
max_length: int = 77,
) -> tuple[list]:
try:
tokens = clip.tokenize(text)
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
except requests.HTTPError as exc:
raise RuntimeError(
f"Remote encoder returned HTTP {exc.response.status_code}: {exc.response.text}"
) from exc
except requests.ConnectionError as exc:
raise RuntimeError(
f"Cannot reach Remote Text Encoder. Is the server running?"
) from exc
return ([[cond, {"pooled_output": pooled}]],)
# ── Node: CLIPTextEncodeCoupleRemote (SDXL dual encoder) ─────────────────────
class CLIPTextEncodeCoupleRemote:
"""
SDXL-style dual-encoder conditioning node.
In SDXL, conditioning is produced by two CLIP models:
• clip-l (ViT-L/14) – 77 tokens × 768-dim
• clip-g (ViT-bigG) – 77 tokens × 1280-dim, also provides the pooled vector
The combined conditioning tensor is the concatenation along the last axis,
and the pooled output comes from clip-g only.
Connect:
RemoteDualCLIPLoader.clip → .clip (model 1 = clip-l, model 2 = clip-g)
"""
CATEGORY = "conditioning/remote"
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"clip": (
"CLIP",
{"tooltip": "Dual CLIP from RemoteDualCLIPLoader (clip-l as model 1, clip-g as model 2)."},
),
"text_l": (
"STRING",
{
"default": "",
"multiline": True,
"dynamicPrompts": True,
"tooltip": "Prompt for CLIP-L (typically the short, precise description).",
},
),
"text_g": (
"STRING",