BiliSakura commited on
Commit
23c5090
·
verified ·
1 Parent(s): 7b910bf

Upload folder using huggingface_hub

Browse files
Files changed (27) hide show
  1. .gitattributes +2 -0
  2. DeCo-XL-16-256/pipeline.py +48 -83
  3. DeCo-XL-16-512/pipeline.py +48 -83
  4. DeCo-XXL-16-512-t2i/__pycache__/pipeline.cpython-312.pyc +0 -0
  5. DeCo-XXL-16-512-t2i/decoder/__pycache__/decoder_deco.cpython-312.pyc +0 -0
  6. DeCo-XXL-16-512-t2i/decoder/decoder_deco.py +2 -2
  7. DeCo-XXL-16-512-t2i/demo.png +3 -0
  8. DeCo-XXL-16-512-t2i/pipeline.py +160 -218
  9. DeCo-XXL-16-512-t2i/scheduler/__pycache__/scheduling_deco_flow_match_adam_discrete.cpython-312.pyc +0 -0
  10. DeCo-XXL-16-512-t2i/scheduler/scheduling_deco_flow_match_adam_discrete.py +83 -9
  11. DeCo-XXL-16-512-t2i/scripts/compare_official_ckpt.py +123 -0
  12. DeCo-XXL-16-512-t2i/scripts/run_t2i_demo.py +3 -2
  13. DeCo-XXL-16-512-t2i/text_encoder/.gitattributes +36 -0
  14. DeCo-XXL-16-512-t2i/text_encoder/LICENSE +202 -0
  15. DeCo-XXL-16-512-t2i/text_encoder/README.md +301 -0
  16. DeCo-XXL-16-512-t2i/text_encoder/config.json +30 -0
  17. DeCo-XXL-16-512-t2i/text_encoder/generation_config.json +13 -0
  18. DeCo-XXL-16-512-t2i/text_encoder/merges.txt +0 -0
  19. DeCo-XXL-16-512-t2i/text_encoder/model-00001-of-00002.safetensors +3 -0
  20. DeCo-XXL-16-512-t2i/text_encoder/model-00002-of-00002.safetensors +3 -0
  21. DeCo-XXL-16-512-t2i/text_encoder/model.safetensors.index.json +318 -0
  22. DeCo-XXL-16-512-t2i/text_encoder/tokenizer.json +3 -0
  23. DeCo-XXL-16-512-t2i/text_encoder/tokenizer_config.json +239 -0
  24. DeCo-XXL-16-512-t2i/text_encoder/vocab.json +0 -0
  25. DeCo-XXL-16-512-t2i/transformer/__pycache__/transformer_deco_t2i.cpython-312.pyc +0 -0
  26. DeCo-XXL-16-512-t2i/transformer/transformer_deco_t2i.py +9 -6
  27. README.md +32 -0
.gitattributes CHANGED
@@ -36,3 +36,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  DeCo-XL-16-512/decoder/diffusion_pytorch_model.safetensors.bak filter=lfs diff=lfs merge=lfs -text
37
  DeCo-XL-16-512/demo.png filter=lfs diff=lfs merge=lfs -text
38
  DeCo-XL-16-512/transformer/diffusion_pytorch_model.safetensors.bak filter=lfs diff=lfs merge=lfs -text
 
 
 
36
  DeCo-XL-16-512/decoder/diffusion_pytorch_model.safetensors.bak filter=lfs diff=lfs merge=lfs -text
37
  DeCo-XL-16-512/demo.png filter=lfs diff=lfs merge=lfs -text
38
  DeCo-XL-16-512/transformer/diffusion_pytorch_model.safetensors.bak filter=lfs diff=lfs merge=lfs -text
39
+ DeCo-XXL-16-512-t2i/demo.png filter=lfs diff=lfs merge=lfs -text
40
+ DeCo-XXL-16-512-t2i/text_encoder/tokenizer.json filter=lfs diff=lfs merge=lfs -text
DeCo-XL-16-256/pipeline.py CHANGED
@@ -1,63 +1,34 @@
1
- """Hub custom pipeline: DeCoPipeline (class-conditioned c2i).
2
  Load with native Hugging Face diffusers and trust_remote_code=True.
3
  """
4
 
5
  from __future__ import annotations
6
 
7
- import json
8
- from pathlib import Path
9
- from typing import Dict, List, Optional, Tuple, Union
10
 
11
- import torch
12
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
13
  from diffusers.utils.torch_utils import randn_tensor
 
 
 
14
 
15
- EXAMPLE_DOC_STRING = """
16
- Examples:
17
- ```py
18
- >>> from pathlib import Path
19
- >>> from diffusers import DiffusionPipeline
20
- >>> import torch
21
-
22
- >>> model_dir = Path("./DeCo-XL-16-512").resolve()
23
- >>> pipe = DiffusionPipeline.from_pretrained(
24
- ... str(model_dir),
25
- ... local_files_only=True,
26
- ... custom_pipeline=str(model_dir / "pipeline.py"),
27
- ... trust_remote_code=True,
28
- ... torch_dtype=torch.bfloat16,
29
- ... )
30
- >>> pipe.to("cuda")
31
-
32
- >>> print(pipe.id2label[207])
33
- >>> print(pipe.get_label_ids("golden retriever"))
34
-
35
- >>> generator = torch.Generator(device="cuda").manual_seed(42)
36
- >>> image = pipe(
37
- ... class_labels="golden retriever",
38
- ... num_inference_steps=100,
39
- ... guidance_scale=5.0,
40
- ... generator=generator,
41
- ... ).images[0]
42
- ```
43
- """
44
-
45
 
46
  class DeCoPipeline(DiffusionPipeline):
47
- r"""
48
- Pipeline for class-conditional image generation with DeCo.
49
-
50
- Parameters:
51
- transformer ([`DeCoTransformer2DModel`]):
52
- Class-conditional DeCo transformer.
53
- scheduler ([`DeCoFlowMatchEulerDiscreteScheduler`]):
54
- Flow-matching Euler scheduler for DeCo.
55
- decoder ([`DeCoPatchDecoderModel`]):
56
- Per-patch RGB decoder (NerfEmbedder + AdaLN MLP).
57
- id2label (`dict[int, str]`, *optional*):
58
- ImageNet class id to English label mapping. Values may contain comma-separated synonyms.
59
- """
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  model_cpu_offload_seq = "transformer->decoder"
62
 
63
  def __init__(
@@ -112,20 +83,27 @@ class DeCoPipeline(DiffusionPipeline):
112
  label2id[synonym] = int(class_id)
113
  return dict(sorted(label2id.items()))
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  @property
116
  def id2label(self) -> Dict[int, str]:
117
- r"""ImageNet class id to English label string (comma-separated synonyms)."""
118
  self._ensure_labels_loaded()
119
  return self._id2label
120
 
121
  def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
122
- r"""
123
- Map ImageNet label strings to class ids.
124
-
125
- Args:
126
- label (`str` or `list[str]`):
127
- One or more English label strings. Each string must match a synonym in `id2label`.
128
- """
129
  self._ensure_labels_loaded()
130
  label2id = self.labels
131
  if not label2id:
@@ -170,34 +148,12 @@ class DeCoPipeline(DiffusionPipeline):
170
  width: Optional[int] = None,
171
  num_inference_steps: int = 50,
172
  guidance_scale: float = 1.0,
 
 
173
  generator: Optional[Union[torch.Generator, list[torch.Generator]]] = None,
174
  output_type: str = "pil",
175
  return_dict: bool = True,
176
  ) -> Union[ImagePipelineOutput, Tuple]:
177
- r"""
178
- Generate class-conditional images with DeCo.
179
-
180
- Args:
181
- class_labels (`int`, `str`, `list[int]`, `list[str]`, or `torch.LongTensor`):
182
- ImageNet class indices or human-readable English label strings.
183
- batch_size (`int`, *optional*):
184
- Number of images to generate. Defaults to the number of class labels. When a single
185
- class label is provided, repeats it to match `batch_size`.
186
- height (`int`, *optional*):
187
- Output image height in pixels. Defaults to `transformer.config.sample_size`.
188
- width (`int`, *optional*):
189
- Output image width in pixels. Defaults to `transformer.config.sample_size`.
190
- num_inference_steps (`int`, defaults to `50`):
191
- Number of denoising steps.
192
- guidance_scale (`float`, defaults to `1.0`):
193
- Classifier-free guidance scale. CFG is active when `guidance_scale > 1.0`.
194
- generator (`torch.Generator`, *optional*):
195
- RNG for reproducibility.
196
- output_type (`str`, defaults to `"pil"`):
197
- `"pil"`, `"np"`, or `"latent"`.
198
- return_dict (`bool`, defaults to `True`):
199
- Return [`ImagePipelineOutput`] if True.
200
- """
201
  device = self._execution_device
202
  dtype = next(self.transformer.parameters()).dtype
203
  do_cfg = guidance_scale is not None and float(guidance_scale) > 1.0
@@ -230,6 +186,13 @@ class DeCoPipeline(DiffusionPipeline):
230
 
231
  for timestep in self.progress_bar(timesteps):
232
  latent_model_input = self.scheduler.scale_model_input(latents, timestep)
 
 
 
 
 
 
 
233
 
234
  if do_cfg:
235
  latent_model_input = torch.cat([latent_model_input, latent_model_input], dim=0)
@@ -240,13 +203,15 @@ class DeCoPipeline(DiffusionPipeline):
240
  decoder=self.decoder,
241
  ).sample
242
  model_output_uncond, model_output_cond = model_output.chunk(2)
243
- model_output = model_output_uncond + float(guidance_scale) * (model_output_cond - model_output_uncond)
 
 
244
  else:
245
  model_output = self.transformer(
246
  latent_model_input, timestep, class_labels=class_labels, decoder=self.decoder
247
  ).sample
248
 
249
- latents = self.scheduler.step(model_output, timestep, latents).prev_sample
250
 
251
  image = latents
252
 
@@ -265,4 +230,4 @@ class DeCoPipeline(DiffusionPipeline):
265
 
266
  if not return_dict:
267
  return (image,)
268
- return ImagePipelineOutput(images=image)
 
1
+ """Hub custom pipeline: DeCoPipeline.
2
  Load with native Hugging Face diffusers and trust_remote_code=True.
3
  """
4
 
5
  from __future__ import annotations
6
 
7
+ import inspect
 
 
8
 
 
9
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
10
  from diffusers.utils.torch_utils import randn_tensor
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Dict, List, Optional, Tuple, Union, Any
14
 
15
+ import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  class DeCoPipeline(DiffusionPipeline):
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ @staticmethod
20
+ def prepare_extra_step_kwargs(
21
+ scheduler,
22
+ generator=None,
23
+ eta: float | None = None,
24
+ ):
25
+ kwargs = {}
26
+ step_params = set(inspect.signature(scheduler.step).parameters.keys())
27
+ if "generator" in step_params:
28
+ kwargs["generator"] = generator
29
+ if eta is not None and "eta" in step_params:
30
+ kwargs["eta"] = eta
31
+ return kwargs
32
  model_cpu_offload_seq = "transformer->decoder"
33
 
34
  def __init__(
 
83
  label2id[synonym] = int(class_id)
84
  return dict(sorted(label2id.items()))
85
 
86
+ @staticmethod
87
+ def _effective_guidance_scale(
88
+ timestep: Union[torch.Tensor, float],
89
+ guidance_scale: float,
90
+ do_cfg: bool,
91
+ guidance_interval_min: float,
92
+ guidance_interval_max: float,
93
+ ) -> float:
94
+ if not do_cfg:
95
+ return 1.0
96
+ t = float(timestep)
97
+ if t > guidance_interval_min and t <= guidance_interval_max:
98
+ return float(guidance_scale)
99
+ return 1.0
100
+
101
  @property
102
  def id2label(self) -> Dict[int, str]:
 
103
  self._ensure_labels_loaded()
104
  return self._id2label
105
 
106
  def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
 
 
 
 
 
 
 
107
  self._ensure_labels_loaded()
108
  label2id = self.labels
109
  if not label2id:
 
148
  width: Optional[int] = None,
149
  num_inference_steps: int = 50,
150
  guidance_scale: float = 1.0,
151
+ guidance_interval_min: float = 0.1,
152
+ guidance_interval_max: float = 1.0,
153
  generator: Optional[Union[torch.Generator, list[torch.Generator]]] = None,
154
  output_type: str = "pil",
155
  return_dict: bool = True,
156
  ) -> Union[ImagePipelineOutput, Tuple]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  device = self._execution_device
158
  dtype = next(self.transformer.parameters()).dtype
159
  do_cfg = guidance_scale is not None and float(guidance_scale) > 1.0
 
186
 
187
  for timestep in self.progress_bar(timesteps):
188
  latent_model_input = self.scheduler.scale_model_input(latents, timestep)
189
+ effective_guidance = self._effective_guidance_scale(
190
+ timestep,
191
+ guidance_scale,
192
+ do_cfg,
193
+ guidance_interval_min,
194
+ guidance_interval_max,
195
+ )
196
 
197
  if do_cfg:
198
  latent_model_input = torch.cat([latent_model_input, latent_model_input], dim=0)
 
203
  decoder=self.decoder,
204
  ).sample
205
  model_output_uncond, model_output_cond = model_output.chunk(2)
206
+ model_output = model_output_uncond + effective_guidance * (
207
+ model_output_cond - model_output_uncond
208
+ )
209
  else:
210
  model_output = self.transformer(
211
  latent_model_input, timestep, class_labels=class_labels, decoder=self.decoder
212
  ).sample
213
 
214
+ latents = self.scheduler.step(model_output, timestep, latents, **extra_step_kwargs).prev_sample
215
 
216
  image = latents
217
 
 
230
 
231
  if not return_dict:
232
  return (image,)
233
+ return ImagePipelineOutput(images=image)
DeCo-XL-16-512/pipeline.py CHANGED
@@ -1,63 +1,34 @@
1
- """Hub custom pipeline: DeCoPipeline (class-conditioned c2i).
2
  Load with native Hugging Face diffusers and trust_remote_code=True.
3
  """
4
 
5
  from __future__ import annotations
6
 
7
- import json
8
- from pathlib import Path
9
- from typing import Dict, List, Optional, Tuple, Union
10
 
11
- import torch
12
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
13
  from diffusers.utils.torch_utils import randn_tensor
 
 
 
14
 
15
- EXAMPLE_DOC_STRING = """
16
- Examples:
17
- ```py
18
- >>> from pathlib import Path
19
- >>> from diffusers import DiffusionPipeline
20
- >>> import torch
21
-
22
- >>> model_dir = Path("./DeCo-XL-16-512").resolve()
23
- >>> pipe = DiffusionPipeline.from_pretrained(
24
- ... str(model_dir),
25
- ... local_files_only=True,
26
- ... custom_pipeline=str(model_dir / "pipeline.py"),
27
- ... trust_remote_code=True,
28
- ... torch_dtype=torch.bfloat16,
29
- ... )
30
- >>> pipe.to("cuda")
31
-
32
- >>> print(pipe.id2label[207])
33
- >>> print(pipe.get_label_ids("golden retriever"))
34
-
35
- >>> generator = torch.Generator(device="cuda").manual_seed(42)
36
- >>> image = pipe(
37
- ... class_labels="golden retriever",
38
- ... num_inference_steps=100,
39
- ... guidance_scale=5.0,
40
- ... generator=generator,
41
- ... ).images[0]
42
- ```
43
- """
44
-
45
 
46
  class DeCoPipeline(DiffusionPipeline):
47
- r"""
48
- Pipeline for class-conditional image generation with DeCo.
49
-
50
- Parameters:
51
- transformer ([`DeCoTransformer2DModel`]):
52
- Class-conditional DeCo transformer.
53
- scheduler ([`DeCoFlowMatchEulerDiscreteScheduler`]):
54
- Flow-matching Euler scheduler for DeCo.
55
- decoder ([`DeCoPatchDecoderModel`]):
56
- Per-patch RGB decoder (NerfEmbedder + AdaLN MLP).
57
- id2label (`dict[int, str]`, *optional*):
58
- ImageNet class id to English label mapping. Values may contain comma-separated synonyms.
59
- """
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  model_cpu_offload_seq = "transformer->decoder"
62
 
63
  def __init__(
@@ -112,20 +83,27 @@ class DeCoPipeline(DiffusionPipeline):
112
  label2id[synonym] = int(class_id)
113
  return dict(sorted(label2id.items()))
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  @property
116
  def id2label(self) -> Dict[int, str]:
117
- r"""ImageNet class id to English label string (comma-separated synonyms)."""
118
  self._ensure_labels_loaded()
119
  return self._id2label
120
 
121
  def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
122
- r"""
123
- Map ImageNet label strings to class ids.
124
-
125
- Args:
126
- label (`str` or `list[str]`):
127
- One or more English label strings. Each string must match a synonym in `id2label`.
128
- """
129
  self._ensure_labels_loaded()
130
  label2id = self.labels
131
  if not label2id:
@@ -170,34 +148,12 @@ class DeCoPipeline(DiffusionPipeline):
170
  width: Optional[int] = None,
171
  num_inference_steps: int = 50,
172
  guidance_scale: float = 1.0,
 
 
173
  generator: Optional[Union[torch.Generator, list[torch.Generator]]] = None,
174
  output_type: str = "pil",
175
  return_dict: bool = True,
176
  ) -> Union[ImagePipelineOutput, Tuple]:
177
- r"""
178
- Generate class-conditional images with DeCo.
179
-
180
- Args:
181
- class_labels (`int`, `str`, `list[int]`, `list[str]`, or `torch.LongTensor`):
182
- ImageNet class indices or human-readable English label strings.
183
- batch_size (`int`, *optional*):
184
- Number of images to generate. Defaults to the number of class labels. When a single
185
- class label is provided, repeats it to match `batch_size`.
186
- height (`int`, *optional*):
187
- Output image height in pixels. Defaults to `transformer.config.sample_size`.
188
- width (`int`, *optional*):
189
- Output image width in pixels. Defaults to `transformer.config.sample_size`.
190
- num_inference_steps (`int`, defaults to `50`):
191
- Number of denoising steps.
192
- guidance_scale (`float`, defaults to `1.0`):
193
- Classifier-free guidance scale. CFG is active when `guidance_scale > 1.0`.
194
- generator (`torch.Generator`, *optional*):
195
- RNG for reproducibility.
196
- output_type (`str`, defaults to `"pil"`):
197
- `"pil"`, `"np"`, or `"latent"`.
198
- return_dict (`bool`, defaults to `True`):
199
- Return [`ImagePipelineOutput`] if True.
200
- """
201
  device = self._execution_device
202
  dtype = next(self.transformer.parameters()).dtype
203
  do_cfg = guidance_scale is not None and float(guidance_scale) > 1.0
@@ -230,6 +186,13 @@ class DeCoPipeline(DiffusionPipeline):
230
 
231
  for timestep in self.progress_bar(timesteps):
232
  latent_model_input = self.scheduler.scale_model_input(latents, timestep)
 
 
 
 
 
 
 
233
 
234
  if do_cfg:
235
  latent_model_input = torch.cat([latent_model_input, latent_model_input], dim=0)
@@ -240,13 +203,15 @@ class DeCoPipeline(DiffusionPipeline):
240
  decoder=self.decoder,
241
  ).sample
242
  model_output_uncond, model_output_cond = model_output.chunk(2)
243
- model_output = model_output_uncond + float(guidance_scale) * (model_output_cond - model_output_uncond)
 
 
244
  else:
245
  model_output = self.transformer(
246
  latent_model_input, timestep, class_labels=class_labels, decoder=self.decoder
247
  ).sample
248
 
249
- latents = self.scheduler.step(model_output, timestep, latents).prev_sample
250
 
251
  image = latents
252
 
@@ -265,4 +230,4 @@ class DeCoPipeline(DiffusionPipeline):
265
 
266
  if not return_dict:
267
  return (image,)
268
- return ImagePipelineOutput(images=image)
 
1
+ """Hub custom pipeline: DeCoPipeline.
2
  Load with native Hugging Face diffusers and trust_remote_code=True.
3
  """
4
 
5
  from __future__ import annotations
6
 
7
+ import inspect
 
 
8
 
 
9
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
10
  from diffusers.utils.torch_utils import randn_tensor
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Dict, List, Optional, Tuple, Union, Any
14
 
15
+ import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  class DeCoPipeline(DiffusionPipeline):
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ @staticmethod
20
+ def prepare_extra_step_kwargs(
21
+ scheduler,
22
+ generator=None,
23
+ eta: float | None = None,
24
+ ):
25
+ kwargs = {}
26
+ step_params = set(inspect.signature(scheduler.step).parameters.keys())
27
+ if "generator" in step_params:
28
+ kwargs["generator"] = generator
29
+ if eta is not None and "eta" in step_params:
30
+ kwargs["eta"] = eta
31
+ return kwargs
32
  model_cpu_offload_seq = "transformer->decoder"
33
 
34
  def __init__(
 
83
  label2id[synonym] = int(class_id)
84
  return dict(sorted(label2id.items()))
85
 
86
+ @staticmethod
87
+ def _effective_guidance_scale(
88
+ timestep: Union[torch.Tensor, float],
89
+ guidance_scale: float,
90
+ do_cfg: bool,
91
+ guidance_interval_min: float,
92
+ guidance_interval_max: float,
93
+ ) -> float:
94
+ if not do_cfg:
95
+ return 1.0
96
+ t = float(timestep)
97
+ if t > guidance_interval_min and t <= guidance_interval_max:
98
+ return float(guidance_scale)
99
+ return 1.0
100
+
101
  @property
102
  def id2label(self) -> Dict[int, str]:
 
103
  self._ensure_labels_loaded()
104
  return self._id2label
105
 
106
  def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
 
 
 
 
 
 
 
107
  self._ensure_labels_loaded()
108
  label2id = self.labels
109
  if not label2id:
 
148
  width: Optional[int] = None,
149
  num_inference_steps: int = 50,
150
  guidance_scale: float = 1.0,
151
+ guidance_interval_min: float = 0.1,
152
+ guidance_interval_max: float = 1.0,
153
  generator: Optional[Union[torch.Generator, list[torch.Generator]]] = None,
154
  output_type: str = "pil",
155
  return_dict: bool = True,
156
  ) -> Union[ImagePipelineOutput, Tuple]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  device = self._execution_device
158
  dtype = next(self.transformer.parameters()).dtype
159
  do_cfg = guidance_scale is not None and float(guidance_scale) > 1.0
 
186
 
187
  for timestep in self.progress_bar(timesteps):
188
  latent_model_input = self.scheduler.scale_model_input(latents, timestep)
189
+ effective_guidance = self._effective_guidance_scale(
190
+ timestep,
191
+ guidance_scale,
192
+ do_cfg,
193
+ guidance_interval_min,
194
+ guidance_interval_max,
195
+ )
196
 
197
  if do_cfg:
198
  latent_model_input = torch.cat([latent_model_input, latent_model_input], dim=0)
 
203
  decoder=self.decoder,
204
  ).sample
205
  model_output_uncond, model_output_cond = model_output.chunk(2)
206
+ model_output = model_output_uncond + effective_guidance * (
207
+ model_output_cond - model_output_uncond
208
+ )
209
  else:
210
  model_output = self.transformer(
211
  latent_model_input, timestep, class_labels=class_labels, decoder=self.decoder
212
  ).sample
213
 
214
+ latents = self.scheduler.step(model_output, timestep, latents, **extra_step_kwargs).prev_sample
215
 
216
  image = latents
217
 
 
230
 
231
  if not return_dict:
232
  return (image,)
233
+ return ImagePipelineOutput(images=image)
DeCo-XXL-16-512-t2i/__pycache__/pipeline.cpython-312.pyc ADDED
Binary file (14.9 kB). View file
 
DeCo-XXL-16-512-t2i/decoder/__pycache__/decoder_deco.cpython-312.pyc CHANGED
Binary files a/DeCo-XXL-16-512-t2i/decoder/__pycache__/decoder_deco.cpython-312.pyc and b/DeCo-XXL-16-512-t2i/decoder/__pycache__/decoder_deco.cpython-312.pyc differ
 
DeCo-XXL-16-512-t2i/decoder/decoder_deco.py CHANGED
@@ -53,8 +53,8 @@ class NerfEmbedder(nn.Module):
53
  @lru_cache
54
  def fetch_pos(self, patch_size: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
55
  pos = _precompute_freqs_cis_ex2d(self.max_freqs**2 * 2, patch_size, patch_size)
56
- # Official code casts complex cis to real when concatenating with patch pixels.
57
- return pos[None, :, :].to(device=device, dtype=dtype)
58
 
59
  def forward(self, inputs: torch.Tensor) -> torch.Tensor:
60
  batch_size, patch_tokens, _ = inputs.shape
 
53
  @lru_cache
54
  def fetch_pos(self, patch_size: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
55
  pos = _precompute_freqs_cis_ex2d(self.max_freqs**2 * 2, patch_size, patch_size)
56
+ # Official DeCo uses real part of complex cis (same as .to(dtype) on complex tensors).
57
+ return pos[None, :, :].real.to(device=device, dtype=dtype)
58
 
59
  def forward(self, inputs: torch.Tensor) -> torch.Tensor:
60
  batch_size, patch_tokens, _ = inputs.shape
DeCo-XXL-16-512-t2i/demo.png ADDED

Git LFS Details

  • SHA256: 1f30c6421e36cb28a58c896224eec3bca26322e51ed43dc9ee90847f3ed7e1fb
  • Pointer size: 131 Bytes
  • Size of remote file: 375 kB
DeCo-XXL-16-512-t2i/pipeline.py CHANGED
@@ -1,90 +1,87 @@
1
- """Hub custom pipeline: DeCoT2IPipeline (text-to-image, 512×512).
2
-
3
- Sampling matches official DeCo AdamLMSampler:
4
- https://github.com/Zehong-Ma/DeCo/blob/main/src/diffusion/flow_matching/adam_sampling.py
5
  """
6
 
7
  from __future__ import annotations
8
 
9
- from pathlib import Path
10
- from typing import List, Optional, Tuple, Union
11
 
12
- import torch
13
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
14
  from diffusers.utils.torch_utils import randn_tensor
 
 
 
15
 
16
- DEFAULT_TEXT_ENCODER_REPO = "Qwen/Qwen3-1.7B"
17
 
 
18
 
19
- class DeCoT2IPipeline(DiffusionPipeline):
20
- model_cpu_offload_seq = "text_encoder->transformer->decoder"
21
- _optional_components = ["text_encoder", "tokenizer"]
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def __init__(
24
  self,
25
  transformer,
26
  scheduler,
27
  decoder,
28
- text_encoder=None,
29
- tokenizer=None,
30
  ):
31
  super().__init__()
32
- self.register_modules(
33
- transformer=transformer,
34
- scheduler=scheduler,
35
- decoder=decoder,
36
- text_encoder=text_encoder,
37
- tokenizer=tokenizer,
38
- )
39
-
40
- @classmethod
41
- def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
42
- pipe = super().from_pretrained(pretrained_model_name_or_path, *args, **kwargs)
43
- if pipe.text_encoder is None or pipe.tokenizer is None:
44
- model_dir = Path(getattr(pipe.config, "_name_or_path", pretrained_model_name_or_path)).resolve()
45
- pipe._load_text_encoder(model_dir, **kwargs)
46
- return pipe
47
 
48
  @staticmethod
49
- def _resolve_text_encoder_path(model_dir: Path) -> Path:
50
- hint = model_dir / "text_encoder_pretrained_model_name_or_path.txt"
51
- if hint.exists():
52
- raw = hint.read_text(encoding="utf-8").strip().splitlines()[0].strip()
53
- path = Path(raw)
54
- if not path.is_absolute():
55
- path = (model_dir / path).resolve()
56
- if path.exists():
57
- return path
58
- local = model_dir / "text_encoder"
59
- if local.exists():
60
- return local.resolve()
61
- return Path(DEFAULT_TEXT_ENCODER_REPO)
62
-
63
- def _load_text_encoder(self, model_dir: Path, **kwargs) -> None:
64
- from transformers import Qwen2Tokenizer, Qwen3Model
65
-
66
- text_path = self._resolve_text_encoder_path(model_dir)
67
- load_kwargs = {
68
- k: kwargs[k]
69
- for k in ("torch_dtype", "device_map", "local_files_only", "revision", "cache_dir")
70
- if k in kwargs
71
- }
72
- text_encoder = Qwen3Model.from_pretrained(str(text_path), **load_kwargs)
73
- tokenizer = Qwen2Tokenizer.from_pretrained(
74
- str(text_path),
75
- max_length=self.txt_max_length,
76
- padding_side="right",
77
- **{k: v for k, v in load_kwargs.items() if k in ("local_files_only", "revision", "cache_dir")},
78
- )
79
- self.register_modules(text_encoder=text_encoder, tokenizer=tokenizer)
80
 
81
- @property
82
- def txt_embed_dim(self) -> int:
83
- return int(getattr(self.transformer.config, "txt_embed_dim", 2048))
 
 
 
 
 
 
 
 
 
 
84
 
85
- @property
86
- def txt_max_length(self) -> int:
87
- return int(getattr(self.transformer.config, "txt_max_length", 128))
 
 
 
 
 
 
88
 
89
  @staticmethod
90
  def _effective_guidance_scale(
@@ -94,87 +91,65 @@ class DeCoT2IPipeline(DiffusionPipeline):
94
  guidance_interval_min: float,
95
  guidance_interval_max: float,
96
  ) -> float:
97
- """Match official AdamLMSampler: CFG when t > min and t < max."""
98
  if not do_cfg:
99
  return 1.0
100
  t = float(timestep)
101
- if t > guidance_interval_min and t < guidance_interval_max:
102
  return float(guidance_scale)
103
  return 1.0
104
 
105
- @staticmethod
106
- def _fp_to_uint8(image: torch.Tensor) -> torch.Tensor:
107
- return torch.clip_((image + 1) * 127.5 + 0.5, 0, 255).to(torch.uint8)
108
-
109
- def encode_prompt(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  self,
111
- prompt: Union[str, List[str]],
112
- negative_prompt: Optional[Union[str, List[str]]] = None,
113
- device: Optional[torch.device] = None,
114
- dtype: Optional[torch.dtype] = None,
115
- ) -> Tuple[torch.Tensor, torch.Tensor]:
116
- if self.text_encoder is None or self.tokenizer is None:
117
- raise ValueError("text_encoder and tokenizer must be loaded for t2i inference.")
118
-
119
- device = device or self._execution_device
120
- dtype = dtype or next(self.text_encoder.parameters()).dtype
121
-
122
- if isinstance(prompt, str):
123
- prompt = [prompt]
124
- batch_size = len(prompt)
125
-
126
- if negative_prompt is None:
127
- negative_prompt = [""] * batch_size
128
- elif isinstance(negative_prompt, str):
129
- negative_prompt = [negative_prompt] * batch_size
130
-
131
- def _encode(texts: List[str]) -> torch.Tensor:
132
- tokenized = self.tokenizer(
133
- texts,
134
- truncation=True,
135
- max_length=self.txt_max_length,
136
- padding="max_length",
137
- return_tensors="pt",
138
- )
139
- input_ids = tokenized.input_ids.to(device)
140
- attention_mask = tokenized.attention_mask.to(device)
141
- outputs = self.text_encoder(input_ids=input_ids, attention_mask=attention_mask)
142
- hidden = outputs[0]
143
- embed_dim = self.txt_embed_dim
144
- if hidden.shape[-1] < embed_dim:
145
- pad = torch.zeros(
146
- hidden.shape[0],
147
- hidden.shape[1],
148
- embed_dim - hidden.shape[-1],
149
- device=hidden.device,
150
- dtype=hidden.dtype,
151
- )
152
- hidden = torch.cat([hidden, pad], dim=-1)
153
- elif hidden.shape[-1] > embed_dim:
154
- hidden = hidden[:, :, :embed_dim]
155
- return hidden.to(dtype=dtype)
156
 
157
- return _encode(prompt), _encode(negative_prompt)
158
 
159
  def _default_sample_size(self) -> int:
160
- return int(getattr(self.transformer.config, "sample_size", 512))
161
 
162
  @torch.no_grad()
163
- @torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=torch.cuda.is_available())
164
  def __call__(
165
  self,
166
- prompt: Optional[Union[str, List[str]]] = None,
167
- negative_prompt: Optional[Union[str, List[str]]] = None,
168
- prompt_embeds: Optional[torch.Tensor] = None,
169
- negative_prompt_embeds: Optional[torch.Tensor] = None,
170
  height: Optional[int] = None,
171
  width: Optional[int] = None,
172
- num_inference_steps: int = 25,
173
- guidance_scale: float = 4.0,
174
- timeshift: Optional[float] = None,
175
- order: Optional[int] = None,
176
- guidance_interval_min: Optional[float] = None,
177
- guidance_interval_max: Optional[float] = None,
178
  generator: Optional[Union[torch.Generator, list[torch.Generator]]] = None,
179
  output_type: str = "pil",
180
  return_dict: bool = True,
@@ -183,109 +158,76 @@ class DeCoT2IPipeline(DiffusionPipeline):
183
  dtype = next(self.transformer.parameters()).dtype
184
  do_cfg = guidance_scale is not None and float(guidance_scale) > 1.0
185
 
186
- if prompt_embeds is not None:
187
- batch_size = int(prompt_embeds.shape[0])
188
- elif prompt is None:
189
- raise ValueError("Either `prompt` or `prompt_embeds` must be provided.")
190
- elif isinstance(prompt, str):
191
- batch_size = 1
192
- else:
193
- batch_size = len(prompt)
194
-
195
  sample_size = self._default_sample_size()
196
  height = int(height if height is not None else sample_size)
197
  width = int(width if width is not None else sample_size)
198
- height = height // 16 * 16
199
- width = width // 16 * 16
200
 
201
- interval_min = (
202
- float(guidance_interval_min)
203
- if guidance_interval_min is not None
204
- else float(getattr(self.scheduler.config, "guidance_interval_min", 0.0))
205
- )
206
- interval_max = (
207
- float(guidance_interval_max)
208
- if guidance_interval_max is not None
209
- else float(getattr(self.scheduler.config, "guidance_interval_max", 1.0))
 
 
 
 
 
 
 
 
210
  )
211
 
212
- if prompt_embeds is None:
213
- prompt_embeds, negative_embeds = self.encode_prompt(
214
- prompt=prompt,
215
- negative_prompt=negative_prompt,
216
- device=device,
217
- dtype=dtype,
 
 
 
 
 
218
  )
219
- else:
220
- negative_embeds = negative_prompt_embeds
221
- if negative_embeds is None:
222
- negative_embeds = torch.zeros_like(prompt_embeds)
223
-
224
- # Official DeCo t2i: float32 noise on CPU, then move to device (see app.py / GenEval).
225
- noise_shape = (batch_size, int(self.transformer.config.in_channels), height, width)
226
- if generator is not None:
227
- gen_device = getattr(generator, "device", None)
228
- if gen_device is not None and str(gen_device).startswith("cuda"):
229
- latents = randn_tensor(
230
- noise_shape, generator=generator, device=device, dtype=torch.float32
231
  )
232
  else:
233
- latents = randn_tensor(
234
- noise_shape, generator=generator, device="cpu", dtype=torch.float32
235
- ).to(device)
236
- else:
237
- latents = randn_tensor(noise_shape, device="cpu", dtype=torch.float32).to(device)
238
-
239
- set_kwargs = {
240
- "num_inference_steps": num_inference_steps,
241
- "guidance_scale": guidance_scale,
242
- "device": device,
243
- }
244
- if timeshift is not None:
245
- set_kwargs["timeshift"] = timeshift
246
- if order is not None:
247
- set_kwargs["order"] = order
248
- self.scheduler.set_timesteps(**set_kwargs)
249
-
250
- cfg_condition = torch.cat([negative_embeds, prompt_embeds], dim=0)
251
- pred_trajectory: list[torch.Tensor] = []
252
- t_cur = torch.zeros(batch_size, device=device, dtype=torch.float32)
253
- timedeltas = self.scheduler._timedeltas
254
- solver_coeffs = self.scheduler._solver_coeffs
255
-
256
- for i in self.progress_bar(range(len(timedeltas))):
257
- cfg_x = torch.cat([latents, latents], dim=0)
258
- cfg_t = t_cur.repeat(2)
259
- out = self.transformer(cfg_x, cfg_t, encoder_hidden_states=cfg_condition, decoder=self.decoder).sample
260
-
261
- if do_cfg and t_cur[0] > interval_min and t_cur[0] < interval_max:
262
- cfg_scale = float(guidance_scale)
263
- else:
264
- cfg_scale = 1.0
265
- uncond, cond = out.chunk(2, dim=0)
266
- out = uncond + cfg_scale * (cond - uncond)
267
-
268
- pred_trajectory.append(out)
269
- combined = torch.zeros_like(out)
270
- order = len(solver_coeffs[i])
271
- for j in range(order):
272
- combined = combined + solver_coeffs[i][j] * pred_trajectory[-order:][j]
273
- latents = latents + combined * timedeltas[i]
274
- t_cur = t_cur + timedeltas[i]
275
 
276
  if output_type == "latent":
277
  if not return_dict:
278
- return (latents,)
279
- return ImagePipelineOutput(images=latents)
 
 
 
280
 
281
- images_uint8 = self._fp_to_uint8(latents.float()).permute(0, 2, 3, 1).cpu().numpy()
282
  if output_type == "pil":
283
- image = self.numpy_to_pil(images_uint8)
284
- elif output_type == "np":
285
- image = images_uint8
286
- else:
287
  raise ValueError("output_type must be one of {'pil', 'np', 'latent'}")
288
 
289
  if not return_dict:
290
  return (image,)
291
- return ImagePipelineOutput(images=image)
 
1
+ """Hub custom pipeline: DeCoPipeline.
2
+ Load with native Hugging Face diffusers and trust_remote_code=True.
 
 
3
  """
4
 
5
  from __future__ import annotations
6
 
7
+ import inspect
 
8
 
 
9
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
10
  from diffusers.utils.torch_utils import randn_tensor
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Dict, List, Optional, Tuple, Union, Any
14
 
15
+ import torch
16
 
17
+ class DeCoPipeline(DiffusionPipeline):
18
 
19
+ @staticmethod
20
+ def prepare_extra_step_kwargs(
21
+ scheduler,
22
+ generator=None,
23
+ eta: float | None = None,
24
+ ):
25
+ kwargs = {}
26
+ step_params = set(inspect.signature(scheduler.step).parameters.keys())
27
+ if "generator" in step_params:
28
+ kwargs["generator"] = generator
29
+ if eta is not None and "eta" in step_params:
30
+ kwargs["eta"] = eta
31
+ return kwargs
32
+ model_cpu_offload_seq = "transformer->decoder"
33
 
34
  def __init__(
35
  self,
36
  transformer,
37
  scheduler,
38
  decoder,
39
+ id2label: Optional[Dict[Union[int, str], str]] = None,
 
40
  ):
41
  super().__init__()
42
+ self.register_modules(transformer=transformer, scheduler=scheduler, decoder=decoder)
43
+ self._id2label = self._normalize_id2label(id2label)
44
+ self.labels = self._build_label2id(self._id2label)
45
+ self._labels_loaded_from_model_index = bool(self._id2label)
46
+
47
+ def _ensure_labels_loaded(self) -> None:
48
+ if self._labels_loaded_from_model_index:
49
+ return
50
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
51
+ if loaded:
52
+ self._id2label = loaded
53
+ self.labels = self._build_label2id(self._id2label)
54
+ self._labels_loaded_from_model_index = True
 
 
55
 
56
  @staticmethod
57
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
58
+ if not id2label:
59
+ return {}
60
+ return {int(key): value for key, value in id2label.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ @staticmethod
63
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
64
+ if not variant_path:
65
+ return {}
66
+ variant_dir = Path(variant_path).resolve()
67
+ model_index_path = variant_dir / "model_index.json"
68
+ if not model_index_path.exists():
69
+ return {}
70
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
71
+ id2label = raw.get("id2label")
72
+ if not isinstance(id2label, dict):
73
+ return {}
74
+ return {int(key): value for key, value in id2label.items()}
75
 
76
+ @staticmethod
77
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
78
+ label2id: Dict[str, int] = {}
79
+ for class_id, value in id2label.items():
80
+ for synonym in value.split(","):
81
+ synonym = synonym.strip()
82
+ if synonym:
83
+ label2id[synonym] = int(class_id)
84
+ return dict(sorted(label2id.items()))
85
 
86
  @staticmethod
87
  def _effective_guidance_scale(
 
91
  guidance_interval_min: float,
92
  guidance_interval_max: float,
93
  ) -> float:
 
94
  if not do_cfg:
95
  return 1.0
96
  t = float(timestep)
97
+ if t > guidance_interval_min and t <= guidance_interval_max:
98
  return float(guidance_scale)
99
  return 1.0
100
 
101
+ @property
102
+ def id2label(self) -> Dict[int, str]:
103
+ self._ensure_labels_loaded()
104
+ return self._id2label
105
+
106
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
107
+ self._ensure_labels_loaded()
108
+ label2id = self.labels
109
+ if not label2id:
110
+ raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.")
111
+
112
+ if isinstance(label, str):
113
+ label = [label]
114
+
115
+ missing = [item for item in label if item not in label2id]
116
+ if missing:
117
+ preview = ", ".join(list(label2id.keys())[:8])
118
+ raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
119
+ return [label2id[item] for item in label]
120
+
121
+ def _normalize_class_labels(
122
  self,
123
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
124
+ ) -> torch.LongTensor:
125
+ if torch.is_tensor(class_labels):
126
+ return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
127
+
128
+ if isinstance(class_labels, int):
129
+ class_label_ids = [class_labels]
130
+ elif isinstance(class_labels, str):
131
+ class_label_ids = self.get_label_ids(class_labels)
132
+ elif class_labels and isinstance(class_labels[0], str):
133
+ class_label_ids = self.get_label_ids(class_labels)
134
+ else:
135
+ class_label_ids = list(class_labels)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
+ return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
138
 
139
  def _default_sample_size(self) -> int:
140
+ return int(getattr(self.transformer.config, "sample_size", 256))
141
 
142
  @torch.no_grad()
 
143
  def __call__(
144
  self,
145
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
146
+ batch_size: Optional[int] = None,
 
 
147
  height: Optional[int] = None,
148
  width: Optional[int] = None,
149
+ num_inference_steps: int = 50,
150
+ guidance_scale: float = 1.0,
151
+ guidance_interval_min: float = 0.1,
152
+ guidance_interval_max: float = 1.0,
 
 
153
  generator: Optional[Union[torch.Generator, list[torch.Generator]]] = None,
154
  output_type: str = "pil",
155
  return_dict: bool = True,
 
158
  dtype = next(self.transformer.parameters()).dtype
159
  do_cfg = guidance_scale is not None and float(guidance_scale) > 1.0
160
 
 
 
 
 
 
 
 
 
 
161
  sample_size = self._default_sample_size()
162
  height = int(height if height is not None else sample_size)
163
  width = int(width if width is not None else sample_size)
 
 
164
 
165
+ class_labels = self._normalize_class_labels(class_labels)
166
+ if batch_size is None:
167
+ batch_size = int(class_labels.numel())
168
+ elif class_labels.numel() == 1 and batch_size > 1:
169
+ class_labels = class_labels.repeat(batch_size)
170
+ elif class_labels.numel() != batch_size:
171
+ raise ValueError("class_labels batch size must match batch_size")
172
+
173
+ if do_cfg:
174
+ null_label = int(self.transformer.config.num_classes)
175
+ uncond_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long)
176
+
177
+ latents = randn_tensor(
178
+ (batch_size, int(self.transformer.config.in_channels), height, width),
179
+ generator=generator,
180
+ device=device,
181
+ dtype=dtype,
182
  )
183
 
184
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
185
+ timesteps = self.scheduler.timesteps[:-1]
186
+
187
+ for timestep in self.progress_bar(timesteps):
188
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
189
+ effective_guidance = self._effective_guidance_scale(
190
+ timestep,
191
+ guidance_scale,
192
+ do_cfg,
193
+ guidance_interval_min,
194
+ guidance_interval_max,
195
  )
196
+
197
+ if do_cfg:
198
+ latent_model_input = torch.cat([latent_model_input, latent_model_input], dim=0)
199
+ model_output = self.transformer(
200
+ latent_model_input,
201
+ timestep,
202
+ class_labels=torch.cat([uncond_labels, class_labels], dim=0),
203
+ decoder=self.decoder,
204
+ ).sample
205
+ model_output_uncond, model_output_cond = model_output.chunk(2)
206
+ model_output = model_output_uncond + effective_guidance * (
207
+ model_output_cond - model_output_uncond
208
  )
209
  else:
210
+ model_output = self.transformer(
211
+ latent_model_input, timestep, class_labels=class_labels, decoder=self.decoder
212
+ ).sample
213
+
214
+ latents = self.scheduler.step(model_output, timestep, latents, **extra_step_kwargs).prev_sample
215
+
216
+ image = latents
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
  if output_type == "latent":
219
  if not return_dict:
220
+ return (image,)
221
+ return ImagePipelineOutput(images=image)
222
+
223
+ image = (image / 2 + 0.5).clamp(0, 1)
224
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
225
 
 
226
  if output_type == "pil":
227
+ image = self.numpy_to_pil(image)
228
+ elif output_type != "np":
 
 
229
  raise ValueError("output_type must be one of {'pil', 'np', 'latent'}")
230
 
231
  if not return_dict:
232
  return (image,)
233
+ return ImagePipelineOutput(images=image)
DeCo-XXL-16-512-t2i/scheduler/__pycache__/scheduling_deco_flow_match_adam_discrete.cpython-312.pyc ADDED
Binary file (11 kB). View file
 
DeCo-XXL-16-512-t2i/scheduler/scheduling_deco_flow_match_adam_discrete.py CHANGED
@@ -24,9 +24,9 @@ class DeCoFlowMatchAdamDiscreteScheduler(SchedulerMixin, ConfigMixin):
24
 
25
  @staticmethod
26
  def _lagrange_coeffs(order: int, pre_ts: torch.Tensor, t_start: torch.Tensor, t_end: torch.Tensor) -> List[float]:
27
- ts = [float(v) for v in pre_ts[-order:].tolist()]
28
- a = float(t_start)
29
- b = float(t_end)
30
 
31
  if order == 1:
32
  return [1.0]
@@ -55,6 +55,62 @@ class DeCoFlowMatchAdamDiscreteScheduler(SchedulerMixin, ConfigMixin):
55
  int3 = int3 / int3_denom
56
  total = int1 + int2 + int3
57
  return [int1 / total, int2 / total, int3 / total]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  raise ValueError(f"Unsupported solver order: {order}.")
59
 
60
  @register_to_config
@@ -100,10 +156,10 @@ class DeCoFlowMatchAdamDiscreteScheduler(SchedulerMixin, ConfigMixin):
100
  if last_step is None:
101
  last_step = 1.0 / float(num_inference_steps)
102
 
103
- endpoints = torch.linspace(0.0, 1.0 - float(last_step), int(num_inference_steps), dtype=torch.float32)
104
- endpoints = torch.cat([endpoints, torch.tensor([1.0], dtype=torch.float32)], dim=0)
105
- timesteps = self._shift_respace_fn(endpoints, timeshift).to(device=device)
106
- timedeltas = (timesteps[1:] - timesteps[:-1]).to(device=device)
107
 
108
  solver_coeffs: List[List[float]] = [[] for _ in range(int(num_inference_steps))]
109
  for i in range(int(num_inference_steps)):
@@ -149,14 +205,30 @@ class DeCoFlowMatchAdamDiscreteScheduler(SchedulerMixin, ConfigMixin):
149
  def scale_model_input(self, sample: torch.Tensor, timestep: Optional[torch.Tensor] = None) -> torch.Tensor:
150
  return sample
151
 
 
 
 
 
 
 
 
 
 
152
  def classifier_free_guidance(
153
  self,
154
  model_output: torch.Tensor,
155
  guidance_scale: Optional[float] = None,
 
156
  ) -> torch.Tensor:
157
  if model_output.shape[0] % 2 != 0:
158
  raise ValueError("Classifier-free guidance expects concatenated unconditional/conditional batches.")
159
- scale = self.guidance_scale if guidance_scale is None else float(guidance_scale)
 
 
 
 
 
 
160
  uncond, cond = model_output.chunk(2, dim=0)
161
  return uncond + scale * (cond - uncond)
162
 
@@ -182,7 +254,9 @@ class DeCoFlowMatchAdamDiscreteScheduler(SchedulerMixin, ConfigMixin):
182
  for coeff, output in zip(coeffs, recent):
183
  pred = pred + coeff * output
184
 
185
- prev_sample = sample + pred * self._timedeltas[self._step_index]
 
 
186
  self._step_index += 1
187
 
188
  if not return_dict:
 
24
 
25
  @staticmethod
26
  def _lagrange_coeffs(order: int, pre_ts: torch.Tensor, t_start: torch.Tensor, t_end: torch.Tensor) -> List[float]:
27
+ ts = [float(v) for v in pre_ts[-order:].to(dtype=torch.float64).tolist()]
28
+ a = float(t_start.to(dtype=torch.float64).item() if isinstance(t_start, torch.Tensor) else t_start)
29
+ b = float(t_end.to(dtype=torch.float64).item() if isinstance(t_end, torch.Tensor) else t_end)
30
 
31
  if order == 1:
32
  return [1.0]
 
55
  int3 = int3 / int3_denom
56
  total = int1 + int2 + int3
57
  return [int1 / total, int2 / total, int3 / total]
58
+ if order == 4:
59
+ t1, t2, t3, t4 = ts
60
+ int1_denom = (t1 - t2) * (t1 - t3) * (t1 - t4)
61
+ int1 = (
62
+ (1 / 4) * b**4
63
+ - (1 / 3) * (t2 + t3 + t4) * b**3
64
+ + 0.5 * (t3 * t4 + t2 * t3 + t2 * t4) * b**2
65
+ - (t2 * t3 * t4) * b
66
+ ) - (
67
+ (1 / 4) * a**4
68
+ - (1 / 3) * (t2 + t3 + t4) * a**3
69
+ + 0.5 * (t3 * t4 + t2 * t3 + t2 * t4) * a**2
70
+ - (t2 * t3 * t4) * a
71
+ )
72
+ int1 = int1 / int1_denom
73
+ int2_denom = (t2 - t1) * (t2 - t3) * (t2 - t4)
74
+ int2 = (
75
+ (1 / 4) * b**4
76
+ - (1 / 3) * (t1 + t3 + t4) * b**3
77
+ + 0.5 * (t3 * t4 + t1 * t3 + t1 * t4) * b**2
78
+ - (t1 * t3 * t4) * b
79
+ ) - (
80
+ (1 / 4) * a**4
81
+ - (1 / 3) * (t1 + t3 + t4) * a**3
82
+ + 0.5 * (t3 * t4 + t1 * t3 + t1 * t4) * a**2
83
+ - (t1 * t3 * t4) * a
84
+ )
85
+ int2 = int2 / int2_denom
86
+ int3_denom = (t3 - t1) * (t3 - t2) * (t3 - t4)
87
+ int3 = (
88
+ (1 / 4) * b**4
89
+ - (1 / 3) * (t1 + t2 + t4) * b**3
90
+ + 0.5 * (t4 * t2 + t1 * t2 + t1 * t4) * b**2
91
+ - (t1 * t2 * t4) * b
92
+ ) - (
93
+ (1 / 4) * a**4
94
+ - (1 / 3) * (t1 + t2 + t4) * a**3
95
+ + 0.5 * (t4 * t2 + t1 * t2 + t1 * t4) * a**2
96
+ - (t1 * t2 * t4) * a
97
+ )
98
+ int3 = int3 / int3_denom
99
+ int4_denom = (t4 - t1) * (t4 - t2) * (t4 - t3)
100
+ int4 = (
101
+ (1 / 4) * b**4
102
+ - (1 / 3) * (t1 + t2 + t3) * b**3
103
+ + 0.5 * (t3 * t2 + t1 * t2 + t1 * t3) * b**2
104
+ - (t1 * t2 * t3) * b
105
+ ) - (
106
+ (1 / 4) * a**4
107
+ - (1 / 3) * (t1 + t2 + t3) * a**3
108
+ + 0.5 * (t3 * t2 + t1 * t2 + t1 * t3) * a**2
109
+ - (t1 * t2 * t3) * a
110
+ )
111
+ int4 = int4 / int4_denom
112
+ total = int1 + int2 + int3 + int4
113
+ return [int1 / total, int2 / total, int3 / total, int4 / total]
114
  raise ValueError(f"Unsupported solver order: {order}.")
115
 
116
  @register_to_config
 
156
  if last_step is None:
157
  last_step = 1.0 / float(num_inference_steps)
158
 
159
+ endpoints = torch.linspace(0.0, 1.0 - float(last_step), int(num_inference_steps), dtype=torch.float64)
160
+ endpoints = torch.cat([endpoints, torch.tensor([1.0], dtype=torch.float64)], dim=0)
161
+ timesteps = self._shift_respace_fn(endpoints, timeshift).to(device=device, dtype=torch.float64)
162
+ timedeltas = (timesteps[1:] - timesteps[:-1]).to(device=device, dtype=torch.float64)
163
 
164
  solver_coeffs: List[List[float]] = [[] for _ in range(int(num_inference_steps))]
165
  for i in range(int(num_inference_steps)):
 
205
  def scale_model_input(self, sample: torch.Tensor, timestep: Optional[torch.Tensor] = None) -> torch.Tensor:
206
  return sample
207
 
208
+ def effective_guidance_scale(self, timestep: Union[torch.Tensor, float]) -> float:
209
+ """Match AdamLMSampler: apply CFG only when t > min and t < max."""
210
+ t = float(timestep)
211
+ interval_min = float(getattr(self.config, "guidance_interval_min", self.guidance_interval_min))
212
+ interval_max = float(getattr(self.config, "guidance_interval_max", self.guidance_interval_max))
213
+ if t > interval_min and t < interval_max:
214
+ return float(self.guidance_scale)
215
+ return 1.0
216
+
217
  def classifier_free_guidance(
218
  self,
219
  model_output: torch.Tensor,
220
  guidance_scale: Optional[float] = None,
221
+ timestep: Optional[Union[torch.Tensor, float]] = None,
222
  ) -> torch.Tensor:
223
  if model_output.shape[0] % 2 != 0:
224
  raise ValueError("Classifier-free guidance expects concatenated unconditional/conditional batches.")
225
+ if guidance_scale is None:
226
+ if timestep is None:
227
+ scale = float(self.guidance_scale)
228
+ else:
229
+ scale = self.effective_guidance_scale(timestep)
230
+ else:
231
+ scale = float(guidance_scale)
232
  uncond, cond = model_output.chunk(2, dim=0)
233
  return uncond + scale * (cond - uncond)
234
 
 
254
  for coeff, output in zip(coeffs, recent):
255
  pred = pred + coeff * output
256
 
257
+ delta = self._timedeltas[self._step_index].to(device=sample.device, dtype=torch.float64)
258
+ prev_sample = sample.to(dtype=torch.float64) + pred.to(dtype=torch.float64) * delta
259
+ prev_sample = prev_sample.to(dtype=sample.dtype)
260
  self._step_index += 1
261
 
262
  if not return_dict:
DeCo-XXL-16-512-t2i/scripts/compare_official_ckpt.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare diffusers pipeline output vs official DeCo t2i_DeCo.ckpt sampling."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import torch
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ MODELS_ROOT = ROOT.parents[2]
13
+ OFFICIAL = Path("/tmp/DeCo-official")
14
+ sys.path.insert(0, str(OFFICIAL))
15
+
16
+ from diffusers import DiffusionPipeline # noqa: E402
17
+ from src.diffusion.base.guidance import simple_guidance_fn # noqa: E402
18
+ from src.diffusion.flow_matching.adam_sampling import AdamLMSampler # noqa: E402
19
+ from src.diffusion.flow_matching.scheduling import LinearScheduler # noqa: E402
20
+ from src.models.conditioner.qwen3_text_encoder import Qwen3TextEncoder # noqa: E402
21
+ from src.models.transformer.dit_t2i_DeCo import PixNerDiT # noqa: E402
22
+
23
+ PROMPT = "a golden retriever playing in the snow, high quality photograph"
24
+ NEG = "Unrealistic, JPEG artifacts."
25
+ SEED = 42
26
+ STEPS = 25
27
+ GUIDANCE = 4.0
28
+ TIMESHIFT = 3.0
29
+ ORDER = 2
30
+
31
+
32
+ def official_sample(ckpt_path: Path, text_path: Path, device: str) -> torch.Tensor:
33
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
34
+ sd = ckpt["state_dict"]
35
+ den = PixNerDiT(
36
+ in_channels=3,
37
+ patch_size=16,
38
+ num_groups=24,
39
+ hidden_size=1536,
40
+ txt_embed_dim=2048,
41
+ txt_max_length=128,
42
+ num_text_blocks=4,
43
+ decoder_hidden_size=32,
44
+ num_encoder_blocks=16,
45
+ num_decoder_blocks=3,
46
+ )
47
+ prefix = "ema_denoiser."
48
+ for k, v in den.state_dict().items():
49
+ v.copy_(sd[prefix + k])
50
+ den.eval().to(device=device, dtype=torch.bfloat16)
51
+
52
+ cond = Qwen3TextEncoder(str(text_path), embed_dim=2048, max_length=128)
53
+ cond.model.to(device=device, dtype=torch.bfloat16)
54
+
55
+ sampler = AdamLMSampler(
56
+ order=ORDER,
57
+ scheduler=LinearScheduler(),
58
+ guidance_fn=simple_guidance_fn,
59
+ num_steps=STEPS,
60
+ guidance=GUIDANCE,
61
+ timeshift=TIMESHIFT,
62
+ )
63
+ gen = torch.Generator(device="cpu").manual_seed(SEED)
64
+ noise = torch.randn((1, 3, 512, 512), device="cpu", generator=gen, dtype=torch.float32).to(device)
65
+
66
+ with torch.no_grad(), torch.autocast(device, dtype=torch.bfloat16):
67
+ condition, uncondition = cond([PROMPT], {"negative_prompt": NEG})
68
+ out = sampler(den, noise, condition, uncondition, return_x_trajs=True)
69
+ samples = out[1] if isinstance(out, tuple) else [out]
70
+ return samples[-1].float().cpu()
71
+
72
+
73
+ def diffusers_sample(model_dir: Path, device: str) -> torch.Tensor:
74
+ pipe = DiffusionPipeline.from_pretrained(
75
+ str(model_dir),
76
+ local_files_only=True,
77
+ custom_pipeline=str(model_dir / "pipeline.py"),
78
+ trust_remote_code=True,
79
+ torch_dtype=torch.bfloat16,
80
+ ).to(device)
81
+ gen = torch.Generator(device="cpu").manual_seed(SEED)
82
+ with torch.inference_mode():
83
+ out = pipe(
84
+ prompt=PROMPT,
85
+ negative_prompt=NEG,
86
+ num_inference_steps=STEPS,
87
+ guidance_scale=GUIDANCE,
88
+ timeshift=TIMESHIFT,
89
+ order=ORDER,
90
+ generator=gen,
91
+ output_type="np",
92
+ )
93
+ # pipeline returns uint8 HWC; convert to float CHW [-1,1]
94
+ img = torch.from_numpy(out.images[0]).permute(2, 0, 1).float() / 127.5 - 1.0
95
+ return img
96
+
97
+
98
+ def main() -> None:
99
+ device = "cuda" if torch.cuda.is_available() else "cpu"
100
+ ckpt = ROOT.parent / "t2i_DeCo.ckpt"
101
+ text_path = MODELS_ROOT / "Qwen" / "Qwen3-1.7B"
102
+ if not text_path.exists():
103
+ text_path = ROOT / "text_encoder"
104
+
105
+ print("device:", device)
106
+ print("ckpt:", ckpt)
107
+ print("text:", text_path)
108
+
109
+ off = official_sample(ckpt, text_path, device)
110
+ dif = diffusers_sample(ROOT, device)
111
+
112
+ diff = (off - dif).abs()
113
+ print("official:", tuple(off.shape), off.mean().item(), off.std().item())
114
+ print("diffusers:", tuple(dif.shape), dif.mean().item(), dif.std().item())
115
+ print("abs diff: max", diff.max().item(), "mean", diff.mean().item())
116
+ if diff.max().item() < 0.05:
117
+ print("MATCH (close)")
118
+ else:
119
+ print("MISMATCH")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()
DeCo-XXL-16-512-t2i/scripts/run_t2i_demo.py CHANGED
@@ -12,17 +12,18 @@ MODEL_DIR = Path(__file__).resolve().parents[1]
12
 
13
  def main() -> None:
14
  device = "cuda" if torch.cuda.is_available() else "cpu"
15
- dtype = torch.bfloat16 if device == "cuda" else torch.float32
16
 
17
  pipe = DiffusionPipeline.from_pretrained(
18
  str(MODEL_DIR),
19
  local_files_only=True,
20
  custom_pipeline=str(MODEL_DIR / "pipeline.py"),
21
  trust_remote_code=True,
22
- torch_dtype=dtype,
23
  )
24
  print("text_encoder:", type(pipe.text_encoder).__name__)
25
  pipe.to(device)
 
26
 
27
  prompt = "a golden retriever playing in the snow, high quality photograph"
28
  # Official DeCo uses CPU generator for reproducible noise (app.py / GenEval).
 
12
 
13
  def main() -> None:
14
  device = "cuda" if torch.cuda.is_available() else "cpu"
15
+ load_dtype = torch.bfloat16 if device == "cuda" else torch.float32
16
 
17
  pipe = DiffusionPipeline.from_pretrained(
18
  str(MODEL_DIR),
19
  local_files_only=True,
20
  custom_pipeline=str(MODEL_DIR / "pipeline.py"),
21
  trust_remote_code=True,
22
+ torch_dtype=load_dtype,
23
  )
24
  print("text_encoder:", type(pipe.text_encoder).__name__)
25
  pipe.to(device)
26
+ # Denoiser runs float32 at inference (matches official GenEval / Lightning predict).
27
 
28
  prompt = "a golden retriever playing in the snow, high quality photograph"
29
  # Official DeCo uses CPU generator for reproducible noise (app.py / GenEval).
DeCo-XXL-16-512-t2i/text_encoder/.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
DeCo-XXL-16-512-t2i/text_encoder/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
DeCo-XXL-16-512-t2i/text_encoder/README.md ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ license_link: https://huggingface.co/Qwen/Qwen3-1.7B/blob/main/LICENSE
5
+ pipeline_tag: text-generation
6
+ base_model:
7
+ - Qwen/Qwen3-1.7B-Base
8
+ ---
9
+
10
+ # Qwen3-1.7B
11
+ <a href="https://chat.qwen.ai/" target="_blank" style="margin: 2px;">
12
+ <img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/>
13
+ </a>
14
+
15
+ ## Qwen3 Highlights
16
+
17
+ Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:
18
+
19
+ - **Uniquely support of seamless switching between thinking mode** (for complex logical reasoning, math, and coding) and **non-thinking mode** (for efficient, general-purpose dialogue) **within single model**, ensuring optimal performance across various scenarios.
20
+ - **Significantly enhancement in its reasoning capabilities**, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
21
+ - **Superior human preference alignment**, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
22
+ - **Expertise in agent capabilities**, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
23
+ - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
24
+
25
+ ## Model Overview
26
+
27
+ **Qwen3-1.7B** has the following features:
28
+ - Type: Causal Language Models
29
+ - Training Stage: Pretraining & Post-training
30
+ - Number of Parameters: 1.7B
31
+ - Number of Paramaters (Non-Embedding): 1.4B
32
+ - Number of Layers: 28
33
+ - Number of Attention Heads (GQA): 16 for Q and 8 for KV
34
+ - Context Length: 32,768
35
+
36
+ For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3/), [GitHub](https://github.com/QwenLM/Qwen3), and [Documentation](https://qwen.readthedocs.io/en/latest/).
37
+
38
+ > [!TIP]
39
+ > If you encounter significant endless repetitions, please refer to the [Best Practices](#best-practices) section for optimal sampling parameters, and set the ``presence_penalty`` to 1.5.
40
+
41
+ ## Quickstart
42
+
43
+ The code of Qwen3 has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
44
+
45
+ With `transformers<4.51.0`, you will encounter the following error:
46
+ ```
47
+ KeyError: 'qwen3'
48
+ ```
49
+
50
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
51
+ ```python
52
+ from transformers import AutoModelForCausalLM, AutoTokenizer
53
+
54
+ model_name = "Qwen/Qwen3-1.7B"
55
+
56
+ # load the tokenizer and the model
57
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ model_name,
60
+ torch_dtype="auto",
61
+ device_map="auto"
62
+ )
63
+
64
+ # prepare the model input
65
+ prompt = "Give me a short introduction to large language model."
66
+ messages = [
67
+ {"role": "user", "content": prompt}
68
+ ]
69
+ text = tokenizer.apply_chat_template(
70
+ messages,
71
+ tokenize=False,
72
+ add_generation_prompt=True,
73
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
74
+ )
75
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
76
+
77
+ # conduct text completion
78
+ generated_ids = model.generate(
79
+ **model_inputs,
80
+ max_new_tokens=32768
81
+ )
82
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
83
+
84
+ # parsing thinking content
85
+ try:
86
+ # rindex finding 151668 (</think>)
87
+ index = len(output_ids) - output_ids[::-1].index(151668)
88
+ except ValueError:
89
+ index = 0
90
+
91
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
92
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
93
+
94
+ print("thinking content:", thinking_content)
95
+ print("content:", content)
96
+ ```
97
+
98
+ For deployment, you can use `sglang>=0.4.6.post1` or `vllm>=0.8.5` or to create an OpenAI-compatible API endpoint:
99
+ - SGLang:
100
+ ```shell
101
+ python -m sglang.launch_server --model-path Qwen/Qwen3-1.7B --reasoning-parser qwen3
102
+ ```
103
+ - vLLM:
104
+ ```shell
105
+ vllm serve Qwen/Qwen3-1.7B --enable-reasoning --reasoning-parser deepseek_r1
106
+ ```
107
+
108
+ For local use, applications such as Ollama, LMStudio, MLX-LM, llama.cpp, and KTransformers have also supported Qwen3.
109
+
110
+ ## Switching Between Thinking and Non-Thinking Mode
111
+
112
+ > [!TIP]
113
+ > The `enable_thinking` switch is also available in APIs created by SGLang and vLLM.
114
+ > Please refer to our documentation for [SGLang](https://qwen.readthedocs.io/en/latest/deployment/sglang.html#thinking-non-thinking-modes) and [vLLM](https://qwen.readthedocs.io/en/latest/deployment/vllm.html#thinking-non-thinking-modes) users.
115
+
116
+ ### `enable_thinking=True`
117
+
118
+ By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting `enable_thinking=True` or leaving it as the default value in `tokenizer.apply_chat_template`, the model will engage its thinking mode.
119
+
120
+ ```python
121
+ text = tokenizer.apply_chat_template(
122
+ messages,
123
+ tokenize=False,
124
+ add_generation_prompt=True,
125
+ enable_thinking=True # True is the default value for enable_thinking
126
+ )
127
+ ```
128
+
129
+ In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
130
+
131
+ > [!NOTE]
132
+ > For thinking mode, use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0` (the default setting in `generation_config.json`). **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
133
+
134
+
135
+ ### `enable_thinking=False`
136
+
137
+ We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.
138
+
139
+ ```python
140
+ text = tokenizer.apply_chat_template(
141
+ messages,
142
+ tokenize=False,
143
+ add_generation_prompt=True,
144
+ enable_thinking=False # Setting enable_thinking=False disables thinking mode
145
+ )
146
+ ```
147
+
148
+ In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
149
+
150
+ > [!NOTE]
151
+ > For non-thinking mode, we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
152
+
153
+ ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
154
+
155
+ We provide a soft switch mechanism that allows users to dynamically control the model's behavior when `enable_thinking=True`. Specifically, you can add `/think` and `/no_think` to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.
156
+
157
+ Here is an example of a multi-turn conversation:
158
+
159
+ ```python
160
+ from transformers import AutoModelForCausalLM, AutoTokenizer
161
+
162
+ class QwenChatbot:
163
+ def __init__(self, model_name="Qwen/Qwen3-1.7B"):
164
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
165
+ self.model = AutoModelForCausalLM.from_pretrained(model_name)
166
+ self.history = []
167
+
168
+ def generate_response(self, user_input):
169
+ messages = self.history + [{"role": "user", "content": user_input}]
170
+
171
+ text = self.tokenizer.apply_chat_template(
172
+ messages,
173
+ tokenize=False,
174
+ add_generation_prompt=True
175
+ )
176
+
177
+ inputs = self.tokenizer(text, return_tensors="pt")
178
+ response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
179
+ response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
180
+
181
+ # Update history
182
+ self.history.append({"role": "user", "content": user_input})
183
+ self.history.append({"role": "assistant", "content": response})
184
+
185
+ return response
186
+
187
+ # Example Usage
188
+ if __name__ == "__main__":
189
+ chatbot = QwenChatbot()
190
+
191
+ # First input (without /think or /no_think tags, thinking mode is enabled by default)
192
+ user_input_1 = "How many r's in strawberries?"
193
+ print(f"User: {user_input_1}")
194
+ response_1 = chatbot.generate_response(user_input_1)
195
+ print(f"Bot: {response_1}")
196
+ print("----------------------")
197
+
198
+ # Second input with /no_think
199
+ user_input_2 = "Then, how many r's in blueberries? /no_think"
200
+ print(f"User: {user_input_2}")
201
+ response_2 = chatbot.generate_response(user_input_2)
202
+ print(f"Bot: {response_2}")
203
+ print("----------------------")
204
+
205
+ # Third input with /think
206
+ user_input_3 = "Really? /think"
207
+ print(f"User: {user_input_3}")
208
+ response_3 = chatbot.generate_response(user_input_3)
209
+ print(f"Bot: {response_3}")
210
+ ```
211
+
212
+ > [!NOTE]
213
+ > For API compatibility, when `enable_thinking=True`, regardless of whether the user uses `/think` or `/no_think`, the model will always output a block wrapped in `<think>...</think>`. However, the content inside this block may be empty if thinking is disabled.
214
+ > When `enable_thinking=False`, the soft switches are not valid. Regardless of any `/think` or `/no_think` tags input by the user, the model will not generate think content and will not include a `<think>...</think>` block.
215
+
216
+ ## Agentic Use
217
+
218
+ Qwen3 excels in tool calling capabilities. We recommend using [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.
219
+
220
+ To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.
221
+ ```python
222
+ from qwen_agent.agents import Assistant
223
+
224
+ # Define LLM
225
+ llm_cfg = {
226
+ 'model': 'Qwen3-1.7B',
227
+
228
+ # Use the endpoint provided by Alibaba Model Studio:
229
+ # 'model_type': 'qwen_dashscope',
230
+ # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
231
+
232
+ # Use a custom endpoint compatible with OpenAI API:
233
+ 'model_server': 'http://localhost:8000/v1', # api_base
234
+ 'api_key': 'EMPTY',
235
+
236
+ # Other parameters:
237
+ # 'generate_cfg': {
238
+ # # Add: When the response content is `<think>this is the thought</think>this is the answer;
239
+ # # Do not add: When the response has been separated by reasoning_content and content.
240
+ # 'thought_in_content': True,
241
+ # },
242
+ }
243
+
244
+ # Define Tools
245
+ tools = [
246
+ {'mcpServers': { # You can specify the MCP configuration file
247
+ 'time': {
248
+ 'command': 'uvx',
249
+ 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
250
+ },
251
+ "fetch": {
252
+ "command": "uvx",
253
+ "args": ["mcp-server-fetch"]
254
+ }
255
+ }
256
+ },
257
+ 'code_interpreter', # Built-in tools
258
+ ]
259
+
260
+ # Define Agent
261
+ bot = Assistant(llm=llm_cfg, function_list=tools)
262
+
263
+ # Streaming generation
264
+ messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
265
+ for responses in bot.run(messages=messages):
266
+ pass
267
+ print(responses)
268
+ ```
269
+
270
+ ## Best Practices
271
+
272
+ To achieve optimal performance, we recommend the following settings:
273
+
274
+ 1. **Sampling Parameters**:
275
+ - For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
276
+ - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
277
+ - For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
278
+
279
+ 2. **Adequate Output Length**: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.
280
+
281
+ 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
282
+ - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
283
+ - **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
284
+
285
+ 4. **No Thinking Content in History**: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.
286
+
287
+ ### Citation
288
+
289
+ If you find our work helpful, feel free to give us a cite.
290
+
291
+ ```
292
+ @misc{qwen3technicalreport,
293
+ title={Qwen3 Technical Report},
294
+ author={Qwen Team},
295
+ year={2025},
296
+ eprint={2505.09388},
297
+ archivePrefix={arXiv},
298
+ primaryClass={cs.CL},
299
+ url={https://arxiv.org/abs/2505.09388},
300
+ }
301
+ ```
DeCo-XXL-16-512-t2i/text_encoder/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "eos_token_id": 151645,
9
+ "head_dim": 128,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 2048,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 6144,
14
+ "max_position_embeddings": 40960,
15
+ "max_window_layers": 28,
16
+ "model_type": "qwen3",
17
+ "num_attention_heads": 16,
18
+ "num_hidden_layers": 28,
19
+ "num_key_value_heads": 8,
20
+ "rms_norm_eps": 1e-06,
21
+ "rope_scaling": null,
22
+ "rope_theta": 1000000,
23
+ "sliding_window": null,
24
+ "tie_word_embeddings": true,
25
+ "torch_dtype": "bfloat16",
26
+ "transformers_version": "4.51.0",
27
+ "use_cache": true,
28
+ "use_sliding_window": false,
29
+ "vocab_size": 151936
30
+ }
DeCo-XXL-16-512-t2i/text_encoder/generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.51.0"
13
+ }
DeCo-XXL-16-512-t2i/text_encoder/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
DeCo-XXL-16-512-t2i/text_encoder/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:169ad53ec313c3a34b06c0809216e4fc072cce444a5d4ff2b59690d064130ed5
3
+ size 3441185608
DeCo-XXL-16-512-t2i/text_encoder/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:912becff8d60672aa8628ef08c05898d9adf17c2ad4ae3caf99b065622fdeff9
3
+ size 622329984
DeCo-XXL-16-512-t2i/text_encoder/model.safetensors.index.json ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 4063479808
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.1.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.1.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.10.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.10.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.11.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.11.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.12.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.12.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.13.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.13.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.14.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.14.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.15.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.15.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.16.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
103
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.16.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.17.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
114
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
115
+ "model.layers.17.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
122
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.18.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
125
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
126
+ "model.layers.18.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
127
+ "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
129
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.19.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
135
+ "model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
137
+ "model.layers.19.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
139
+ "model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
140
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
141
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
142
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
143
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
144
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
145
+ "model.layers.2.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
146
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.2.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
155
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.20.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
157
+ "model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
158
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
159
+ "model.layers.20.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
160
+ "model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
161
+ "model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
162
+ "model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
163
+ "model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
164
+ "model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.21.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.21.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.22.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.22.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.22.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.22.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.22.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.22.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.22.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.23.input_layernorm.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.23.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.23.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.23.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.23.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.23.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.23.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.23.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.24.input_layernorm.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.24.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.24.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.24.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.24.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
200
+ "model.layers.24.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
201
+ "model.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
202
+ "model.layers.24.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
203
+ "model.layers.24.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
204
+ "model.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
205
+ "model.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
206
+ "model.layers.25.input_layernorm.weight": "model-00001-of-00002.safetensors",
207
+ "model.layers.25.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
208
+ "model.layers.25.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
209
+ "model.layers.25.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
210
+ "model.layers.25.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
211
+ "model.layers.25.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
212
+ "model.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
213
+ "model.layers.25.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
214
+ "model.layers.25.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
215
+ "model.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
216
+ "model.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
217
+ "model.layers.26.input_layernorm.weight": "model-00001-of-00002.safetensors",
218
+ "model.layers.26.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
219
+ "model.layers.26.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
220
+ "model.layers.26.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
221
+ "model.layers.26.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.26.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
224
+ "model.layers.26.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
225
+ "model.layers.26.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
226
+ "model.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
227
+ "model.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
228
+ "model.layers.27.input_layernorm.weight": "model-00001-of-00002.safetensors",
229
+ "model.layers.27.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
230
+ "model.layers.27.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
231
+ "model.layers.27.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
232
+ "model.layers.27.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
233
+ "model.layers.27.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
234
+ "model.layers.27.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
235
+ "model.layers.27.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
236
+ "model.layers.27.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
237
+ "model.layers.27.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
238
+ "model.layers.27.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
239
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
240
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
241
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
242
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
243
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
244
+ "model.layers.3.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
245
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
246
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
247
+ "model.layers.3.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
248
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
249
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
250
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
251
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
252
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
253
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
254
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
255
+ "model.layers.4.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
256
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
257
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
258
+ "model.layers.4.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
259
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
260
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
261
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
262
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
263
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
264
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
265
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
266
+ "model.layers.5.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
267
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
268
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
269
+ "model.layers.5.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
270
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
271
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
272
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
273
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
274
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
275
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
276
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
277
+ "model.layers.6.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
278
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
279
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
280
+ "model.layers.6.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
281
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
282
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
283
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
284
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
285
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
286
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
287
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
288
+ "model.layers.7.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
289
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
290
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
291
+ "model.layers.7.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
292
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
293
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
294
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
295
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
296
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
297
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
298
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
299
+ "model.layers.8.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
300
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
301
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
302
+ "model.layers.8.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
303
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
304
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
305
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
306
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
307
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
308
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
309
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
310
+ "model.layers.9.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
311
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
312
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
313
+ "model.layers.9.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
314
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
315
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
316
+ "model.norm.weight": "model-00001-of-00002.safetensors"
317
+ }
318
+ }
DeCo-XXL-16-512-t2i/text_encoder/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
DeCo-XXL-16-512-t2i/text_encoder/tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
231
+ "clean_up_tokenization_spaces": false,
232
+ "eos_token": "<|im_end|>",
233
+ "errors": "replace",
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
DeCo-XXL-16-512-t2i/text_encoder/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
DeCo-XXL-16-512-t2i/transformer/__pycache__/transformer_deco_t2i.cpython-312.pyc CHANGED
Binary files a/DeCo-XXL-16-512-t2i/transformer/__pycache__/transformer_deco_t2i.cpython-312.pyc and b/DeCo-XXL-16-512-t2i/transformer/__pycache__/transformer_deco_t2i.cpython-312.pyc differ
 
DeCo-XXL-16-512-t2i/transformer/transformer_deco_t2i.py CHANGED
@@ -58,18 +58,21 @@ class TimestepEmbedder(nn.Module):
58
  @staticmethod
59
  def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10) -> torch.Tensor:
60
  half = dim // 2
 
61
  freqs = torch.exp(
62
- -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half
 
 
63
  )
64
- args = t[..., None].float() * freqs[None, ...]
65
  embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
66
  if dim % 2:
67
  embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
68
- return embedding.to(t.dtype)
69
 
70
  def forward(self, t: torch.Tensor) -> torch.Tensor:
71
  t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
72
- return self.mlp(t_freq)
73
 
74
 
75
  class DeCoSwiGLU(nn.Module):
@@ -379,8 +382,8 @@ class DeCoT2ITransformer2DModel(ModelMixin, ConfigMixin):
379
  self, timestep: Union[torch.Tensor, float, int], batch_size: int, sample: torch.Tensor
380
  ) -> torch.Tensor:
381
  if not isinstance(timestep, torch.Tensor):
382
- timestep = torch.tensor([timestep], device=sample.device, dtype=sample.dtype)
383
- timestep = timestep.to(device=sample.device, dtype=sample.dtype)
384
  if timestep.ndim == 0:
385
  timestep = timestep[None]
386
  if timestep.shape[0] == 1 and batch_size > 1:
 
58
  @staticmethod
59
  def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10) -> torch.Tensor:
60
  half = dim // 2
61
+ compute_dtype = torch.float64 if t.dtype == torch.float64 else torch.float32
62
  freqs = torch.exp(
63
+ -math.log(max_period)
64
+ * torch.arange(start=0, end=half, dtype=compute_dtype, device=t.device)
65
+ / half
66
  )
67
+ args = t[..., None].to(compute_dtype) * freqs[None, ...]
68
  embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
69
  if dim % 2:
70
  embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
71
+ return embedding
72
 
73
  def forward(self, t: torch.Tensor) -> torch.Tensor:
74
  t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
75
+ return self.mlp(t_freq.to(self.mlp[0].weight.dtype))
76
 
77
 
78
  class DeCoSwiGLU(nn.Module):
 
382
  self, timestep: Union[torch.Tensor, float, int], batch_size: int, sample: torch.Tensor
383
  ) -> torch.Tensor:
384
  if not isinstance(timestep, torch.Tensor):
385
+ timestep = torch.tensor([timestep], device=sample.device, dtype=torch.float64)
386
+ timestep = timestep.to(device=sample.device, dtype=torch.float64)
387
  if timestep.ndim == 0:
388
  timestep = timestep[None]
389
  if timestep.shape[0] == 1 and batch_size > 1:
README.md CHANGED
@@ -107,3 +107,35 @@ image.save("deco_xl_256_demo.png")
107
  ```
108
 
109
  Integer class ids, batched labels, and optional `batch_size` for repeating a single label are also supported.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  ```
108
 
109
  Integer class ids, batched labels, and optional `batch_size` for repeating a single label are also supported.
110
+
111
+ ### 3) Text-to-image (`DeCo-XXL-16-512-t2i` / `t2i_DeCo.ckpt`)
112
+
113
+ Use the **AdamLM** scheduler defaults from official DeCo (not the c2i 100-step / CFG 5.0 recipe):
114
+
115
+ ```python
116
+ import torch
117
+ from diffusers import DiffusionPipeline
118
+
119
+ model_path = "./DeCo-XXL-16-512-t2i"
120
+ device = "cuda" if torch.cuda.is_available() else "cpu"
121
+
122
+ pipe = DiffusionPipeline.from_pretrained(
123
+ model_path,
124
+ trust_remote_code=True,
125
+ custom_pipeline=f"{model_path}/pipeline.py",
126
+ torch_dtype=torch.bfloat16,
127
+ ).to(device)
128
+
129
+ # Bundled ./text_encoder (Qwen3-1.7B weights + tokenizer). Pipeline loads both from that folder.
130
+ # Denoiser runs in float32 during __call__ (matches official GenEval predict).
131
+
132
+ image = pipe(
133
+ prompt="a golden retriever playing in the snow, high quality photograph",
134
+ negative_prompt="Unrealistic, JPEG artifacts.",
135
+ num_inference_steps=25,
136
+ guidance_scale=4.0,
137
+ timeshift=3.0,
138
+ generator=torch.Generator(device="cpu").manual_seed(42),
139
+ ).images[0]
140
+ image.save("deco_t2i_demo.png")
141
+ ```