Gemma first implementation · city96/ComfyUI_ExtraModels@0f567fc · GitHub
Skip to content

Commit 0f567fc

Browse files
committed
Gemma first implementation
1 parent c52d827 commit 0f567fc

9 files changed

Lines changed: 2025 additions & 2 deletions

File tree

‎Sana/models/sana_multi_scale.py‎

Lines changed: 2 additions & 0 deletions

‎text_encoders/pixart/tenc.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
import os
2+
import torch
3+
14
from comfy import sd1_clip
25
import comfy.text_encoders.t5
36
import comfy.text_encoders.sd3_clip
47
import comfy.model_management
8+
59
from transformers import T5TokenizerFast
6-
import torch
7-
import os
810

911
class T5XXLModel(comfy.text_encoders.sd3_clip.T5XXLModel):
1012
def __init__(self, **kwargs):

‎text_encoders/sana/config.json‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"architectures": [
3+
"Gemma2ForCausalLM"
4+
],
5+
"attention_bias": false,
6+
"attention_dropout": 0.0,
7+
"attn_logit_softcapping": 50.0,
8+
"bos_token_id": 2,
9+
"cache_implementation": "hybrid",
10+
"eos_token_id": [
11+
1,
12+
107
13+
],
14+
"final_logit_softcapping": 30.0,
15+
"head_dim": 256,
16+
"hidden_act": "gelu_pytorch_tanh",
17+
"hidden_activation": "gelu_pytorch_tanh",
18+
"hidden_size": 2304,
19+
"initializer_range": 0.02,
20+
"intermediate_size": 9216,
21+
"max_position_embeddings": 8192,
22+
"model_type": "gemma2",
23+
"num_attention_heads": 8,
24+
"num_hidden_layers": 26,
25+
"num_key_value_heads": 4,
26+
"pad_token_id": 0,
27+
"query_pre_attn_scalar": 256,
28+
"rms_norm_eps": 1e-06,
29+
"rope_theta": 10000.0,
30+
"sliding_window": 4096,
31+
"torch_dtype": "bfloat16",
32+
"transformers_version": "4.42.4",
33+
"use_cache": true,
34+
"vocab_size": 256000
35+
}

‎text_encoders/sana/gemma.py‎

Lines changed: 379 additions & 0 deletions
Large diffs are not rendered by default.

‎text_encoders/sana/tenc.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import os
2+
import torch
3+
4+
from comfy import sd1_clip
5+
import comfy.model_management
6+
from .gemma import Gemma2Model
7+
8+
from transformers import GemmaTokenizer as TFGemmaTokenizer
9+
10+
class GemmaClipModel(sd1_clip.SDClipModel):
11+
def __init__(self, device="cpu", dtype=None, model_options={}, **kwargs):
12+
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.json")
13+
special_tokens = {"start": 2, "end": 1, "pad": 0}
14+
super().__init__(device=device, layer="last", layer_idx=None, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens=special_tokens, model_class=Gemma2Model, enable_attention_masks=True, return_attention_masks=False, model_options=model_options)
15+
16+
class SanaClipModel(sd1_clip.SD1ClipModel):
17+
def __init__(self, device="cpu", dtype=None, model_options={}):
18+
super().__init__(device=device, dtype=dtype, name="gemma", clip_model=GemmaClipModel, model_options=model_options)
19+
20+
class GemmaTokenizer(sd1_clip.SDTokenizer):
21+
def __init__(self, embedding_directory=None, tokenizer_data={}):
22+
tokenizer_path = os.path.join(
23+
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
24+
"tokenizers", "gemma_tokenizer",
25+
)
26+
# TODO: reenable proper logic here - needs comfy version 44db978 or higher
27+
super().__init__(tokenizer_path, embedding_directory=embedding_directory, pad_with_end=False, embedding_size=2304, embedding_key='gemma', tokenizer_class=TFGemmaTokenizer, has_start_token=False, pad_to_max_length=True, max_length=300, min_length=1)
28+
self.start_token = 2
29+
self.end_token = 1
30+
self.pad_token = 0
31+
32+
def tokenize_with_weights(self, text, return_word_ids=False):
33+
# TODO: see above, this is still just a wrapper for now
34+
tokens = self.tokenizer(
35+
text,
36+
max_length=300,
37+
padding="max_length",
38+
truncation=True,
39+
return_tensors="pt"
40+
)
41+
batched_tokens = [(x.item(), 1.0) for x in tokens.input_ids[0]]
42+
return [batched_tokens]
43+
44+
class SanaTokenizer(sd1_clip.SD1Tokenizer):
45+
def __init__(self, embedding_directory=None, tokenizer_data={}):
46+
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="gemma", tokenizer=GemmaTokenizer)

‎text_encoders/tenc.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
import comfy.sd
55
import comfy.utils
66
import comfy.text_encoders
7+
import comfy.model_management
78

89
from .pixart.tenc import pixart_te, PixArtTokenizer
10+
from .sana.tenc import SanaClipModel, SanaTokenizer
911

1012
class TencType(Enum):
1113
# offset in case we ever integrate w/ original
@@ -44,6 +46,8 @@ class EmptyClass:
4446
for i in range(len(clip_data)):
4547
if "transformer.resblocks.0.ln_1.weight" in clip_data[i]:
4648
clip_data[i] = comfy.utils.clip_text_transformers_convert(clip_data[i], "", "")
49+
elif "model.layers.25.post_feedforward_layernorm.weight" in clip_data[i]:
50+
clip_data[i] = {k[len("model."):]:v for k,v in clip_data[i].items()}
4751
else:
4852
if "text_projection" in clip_data[i]:
4953
clip_data[i]["text_projection.weight"] = clip_data[i]["text_projection"].transpose(0, 1) #old models saved with the CLIPSave node
@@ -54,6 +58,11 @@ class EmptyClass:
5458
if clip_type == TencType.PixArt:
5559
clip_target.clip = pixart_te(**comfy.sd.t5xxl_detect(clip_data))
5660
clip_target.tokenizer = PixArtTokenizer
61+
elif clip_type == TencType.Sana:
62+
clip_target.clip = SanaClipModel
63+
clip_target.tokenizer = SanaTokenizer
64+
else:
65+
raise NotImplementedError(f"Unknown tenc: {clip_type}")
5766

5867
parameters = 0
5968
tokenizer_data = {}
Lines changed: 34 additions & 0 deletions
4.04 MB
Binary file not shown.

0 commit comments

Comments
 (0)