BiliSakura commited on
Commit
4062de2
Β·
verified Β·
1 Parent(s): 0455112

Add JLT-H-1 metadata and update B/L small files

Browse files
.gitattributes CHANGED
@@ -36,3 +36,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  demo.png filter=lfs diff=lfs merge=lfs -text
37
  JLT-B-1/demo.png filter=lfs diff=lfs merge=lfs -text
38
  JLT-L-1/demo.png filter=lfs diff=lfs merge=lfs -text
 
 
36
  demo.png filter=lfs diff=lfs merge=lfs -text
37
  JLT-B-1/demo.png filter=lfs diff=lfs merge=lfs -text
38
  JLT-L-1/demo.png filter=lfs diff=lfs merge=lfs -text
39
+ JLT-H-1/demo.png filter=lfs diff=lfs merge=lfs -text
JLT-B-1/pipeline.py CHANGED
@@ -69,9 +69,11 @@ def _solver_from_scheduler(scheduler) -> str:
69
 
70
  class JLTPipeline(DiffusionPipeline):
71
  r"""
72
- Pipeline for class-conditional image generation with JLT (Clean-Latent JiT).
73
 
74
- Latent models (`in_channels=128`) require a FLUX.2 VAE attached for `output_type="pil"`.
 
 
75
  """
76
 
77
  model_cpu_offload_seq = "transformer->vae"
@@ -372,9 +374,8 @@ class JLTPipeline(DiffusionPipeline):
372
  ImageNet class id(s) or English label(s).
373
  guidance_scale (`float`, *optional*):
374
  CFG scale. Enabled when `guidance_scale > 1`.
375
- noise_scale (`float`, *optional*, defaults to `None`):
376
- Std of the initial noise. JiT/JLT scale this with resolution to keep SNR constant
377
- (`1.0` at 256, `2.0` at 512, `4.0` at 1024). See huggingface/diffusers#13098.
378
  num_inference_steps (`int`, *optional*, defaults to 50):
379
  The number of denoising steps.
380
  output_type (`str`, *optional*, defaults to `"pil"`):
@@ -400,13 +401,10 @@ class JLTPipeline(DiffusionPipeline):
400
  batch_size = len(class_label_ids)
401
  latent_size = int(self.transformer.config.sample_size)
402
  channels = int(self.transformer.config.in_channels)
403
- # Official JiT uses pixel `sample_size`. JLT latent models store the latent grid.
404
- image_size = latent_size * 16 if channels == 128 else latent_size
405
  null_class_val = int(
406
  getattr(self.transformer.config, "num_classes", getattr(self.transformer.config, "num_class_embeds", 1000))
407
  )
408
-
409
- noise_scale = noise_scale if noise_scale is not None else (image_size / 256.0)
410
 
411
  latents = noise_scale * randn_tensor(
412
  shape=(batch_size, channels, latent_size, latent_size),
 
69
 
70
  class JLTPipeline(DiffusionPipeline):
71
  r"""
72
+ Class-conditional JLT sampler.
73
 
74
+ Starts from unit Gaussian noise in FLUX.2 latent space (`noise_scale=1.0`) at the
75
+ trained 256Γ—256 resolution, integrates `JLTScheduler` (Heun, last step Euler),
76
+ applies interval CFG in velocity space, and decodes FLUX.2 latents when a VAE is attached.
77
  """
78
 
79
  model_cpu_offload_seq = "transformer->vae"
 
374
  ImageNet class id(s) or English label(s).
375
  guidance_scale (`float`, *optional*):
376
  CFG scale. Enabled when `guidance_scale > 1`.
377
+ noise_scale (`float`, *optional*, defaults to `1.0`):
378
+ Std of the initial noise. These checkpoints are trained at 256Γ—256 with unit-scale FLUX.2 latents.
 
379
  num_inference_steps (`int`, *optional*, defaults to 50):
380
  The number of denoising steps.
381
  output_type (`str`, *optional*, defaults to `"pil"`):
 
401
  batch_size = len(class_label_ids)
402
  latent_size = int(self.transformer.config.sample_size)
403
  channels = int(self.transformer.config.in_channels)
 
 
404
  null_class_val = int(
405
  getattr(self.transformer.config, "num_classes", getattr(self.transformer.config, "num_class_embeds", 1000))
406
  )
407
+ noise_scale = 1.0 if noise_scale is None else float(noise_scale)
 
408
 
409
  latents = noise_scale * randn_tensor(
410
  shape=(batch_size, channels, latent_size, latent_size),
JLT-B-1/scheduler/scheduling_jlt.py CHANGED
@@ -102,6 +102,7 @@ class JLTScheduler(SchedulerMixin, ConfigMixin):
102
  num_inference_steps: int,
103
  device: Union[str, torch.device, None] = None,
104
  ) -> None:
 
105
  if num_inference_steps < 1:
106
  raise ValueError("num_inference_steps must be >= 1.")
107
  if self.config.solver == "heun" and num_inference_steps < 2:
@@ -208,6 +209,7 @@ class JLTScheduler(SchedulerMixin, ConfigMixin):
208
  prediction_type: Optional[str] = None,
209
  t_eps: Optional[float] = None,
210
  ) -> Union[JLTSchedulerOutput, Tuple[torch.Tensor]]:
 
211
  del generator
212
  step_index = self._resolve_step_index(timestep)
213
  if step_index >= len(self._step_plan):
 
102
  num_inference_steps: int,
103
  device: Union[str, torch.device, None] = None,
104
  ) -> None:
105
+ """Build the `t: 0 β†’ 1` knot schedule and Heun/Euler step plan."""
106
  if num_inference_steps < 1:
107
  raise ValueError("num_inference_steps must be >= 1.")
108
  if self.config.solver == "heun" and num_inference_steps < 2:
 
209
  prediction_type: Optional[str] = None,
210
  t_eps: Optional[float] = None,
211
  ) -> Union[JLTSchedulerOutput, Tuple[torch.Tensor]]:
212
+ """Advance one scheduled ODE step. `model_output` is clean-`x` or velocity."""
213
  del generator
214
  step_index = self._resolve_step_index(timestep)
215
  if step_index >= len(self._step_plan):
JLT-B-1/transformer/transformer_jlt.py CHANGED
@@ -1,4 +1,8 @@
1
- """JLT (Clean-Latent) Transformer for diffusers."""
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
@@ -24,6 +28,8 @@ def rotate_half(x):
24
 
25
 
26
  class JLTRotaryEmbedding(nn.Module):
 
 
27
  def __init__(self, dim, pt_seq_len=16, ft_seq_len=None, theta=10000):
28
  super().__init__()
29
  freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
@@ -52,6 +58,8 @@ def modulate(x, shift, scale):
52
 
53
 
54
  class JLTPatchEmbed(nn.Module):
 
 
55
  def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, bias=True):
56
  super().__init__()
57
  img_size = (img_size, img_size)
@@ -62,15 +70,12 @@ class JLTPatchEmbed(nn.Module):
62
  self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
63
 
64
  def forward(self, x):
65
- batch, _, height, width = x.shape
66
- if height != self.img_size[0] or width != self.img_size[1]:
67
- raise ValueError(
68
- f"Input image size ({height}*{width}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
69
- )
70
  return self.proj(x).flatten(2).transpose(1, 2)
71
 
72
 
73
  class JLTTimestepEmbedder(nn.Module):
 
 
74
  def __init__(self, hidden_size, frequency_embedding_size=256):
75
  super().__init__()
76
  self.mlp = nn.Sequential(
@@ -100,6 +105,8 @@ class JLTTimestepEmbedder(nn.Module):
100
 
101
 
102
  class JLTLabelEmbedder(nn.Module):
 
 
103
  def __init__(self, num_classes, hidden_size):
104
  super().__init__()
105
  self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
@@ -110,6 +117,8 @@ class JLTLabelEmbedder(nn.Module):
110
 
111
 
112
  class JLTAttnProcessor:
 
 
113
  _attention_backend = None
114
  _parallel_config = None
115
 
@@ -141,6 +150,8 @@ class JLTAttnProcessor:
141
 
142
 
143
  class JLTAttention(nn.Module, AttentionModuleMixin):
 
 
144
  _default_processor_cls = JLTAttnProcessor
145
  _available_processors = [JLTAttnProcessor]
146
 
@@ -170,6 +181,8 @@ class JLTAttention(nn.Module, AttentionModuleMixin):
170
 
171
 
172
  class JLTSwiGLUFFN(nn.Module):
 
 
173
  def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
174
  super().__init__()
175
  hidden_dim = int(hidden_dim * 2 / 3)
@@ -184,6 +197,8 @@ class JLTSwiGLUFFN(nn.Module):
184
 
185
 
186
  class JLTBlock(nn.Module):
 
 
187
  def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0, eps=1e-6):
188
  super().__init__()
189
  self.norm1 = RMSNorm(hidden_size, eps=eps)
@@ -209,6 +224,24 @@ class JLTBlock(nn.Module):
209
 
210
 
211
  class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  _supports_gradient_checkpointing = True
213
  _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
214
  _no_split_modules = ["JLTBlock"]
@@ -335,6 +368,7 @@ class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
335
  return_features: bool = False,
336
  feature_layers: Optional[List[int]] = None,
337
  ):
 
338
  t = torch.as_tensor(timestep, device=sample.device)
339
  if t.ndim == 0:
340
  t = t.repeat(sample.shape[0])
 
1
+ """JLT transformer: class-conditional clean-latent (or pixel) DiT.
2
+
3
+ Architecture hyperparameters are read from `config.json` / constructor kwargs.
4
+ Named training presets such as `JiT-B/1` are not part of this module.
5
+ """
6
 
7
  from __future__ import annotations
8
 
 
28
 
29
 
30
  class JLTRotaryEmbedding(nn.Module):
31
+ """2D axial RoPE for JLT attention, matching the official JiT implementation."""
32
+
33
  def __init__(self, dim, pt_seq_len=16, ft_seq_len=None, theta=10000):
34
  super().__init__()
35
  freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
 
58
 
59
 
60
  class JLTPatchEmbed(nn.Module):
61
+ """Conv patch embedder for latents (`patch_size=1`) or pixels."""
62
+
63
  def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, bias=True):
64
  super().__init__()
65
  img_size = (img_size, img_size)
 
70
  self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
71
 
72
  def forward(self, x):
 
 
 
 
 
73
  return self.proj(x).flatten(2).transpose(1, 2)
74
 
75
 
76
  class JLTTimestepEmbedder(nn.Module):
77
+ """Sinusoidal timestep MLP used for adaLN conditioning."""
78
+
79
  def __init__(self, hidden_size, frequency_embedding_size=256):
80
  super().__init__()
81
  self.mlp = nn.Sequential(
 
105
 
106
 
107
  class JLTLabelEmbedder(nn.Module):
108
+ """Class embedding table with one extra null class for CFG."""
109
+
110
  def __init__(self, num_classes, hidden_size):
111
  super().__init__()
112
  self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
 
117
 
118
 
119
  class JLTAttnProcessor:
120
+ """Official JiT-style attention: split `to_q` / `to_k` / `to_v` + `dispatch_attention_fn`."""
121
+
122
  _attention_backend = None
123
  _parallel_config = None
124
 
 
150
 
151
 
152
  class JLTAttention(nn.Module, AttentionModuleMixin):
153
+ """Multi-head self-attention with QK RMSNorm, RoPE, and separate QKV projections."""
154
+
155
  _default_processor_cls = JLTAttnProcessor
156
  _available_processors = [JLTAttnProcessor]
157
 
 
181
 
182
 
183
  class JLTSwiGLUFFN(nn.Module):
184
+ """SwiGLU feed-forward block (`w12` fused, then `w3`)."""
185
+
186
  def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
187
  super().__init__()
188
  hidden_dim = int(hidden_dim * 2 / 3)
 
197
 
198
 
199
  class JLTBlock(nn.Module):
200
+ """Pre-norm transformer block with adaLN-Zero modulation."""
201
+
202
  def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0, eps=1e-6):
203
  super().__init__()
204
  self.norm1 = RMSNorm(hidden_size, eps=eps)
 
224
 
225
 
226
  class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
227
+ r"""
228
+ 2D transformer for class-conditional clean-latent generation ([JLT](https://arxiv.org/abs/2605.27102)).
229
+
230
+ The model predicts the clean sample `x`. Sampling uses [`JLTScheduler`] (`t`: 0 noise β†’ 1 data). Latent
231
+ checkpoints use FLUX.2 latents (`in_channels=128`, `sample_size` is the latent grid).
232
+
233
+ Args:
234
+ sample_size (`int`, defaults to 16): Spatial size of the input grid.
235
+ patch_size (`int`, defaults to 1): Patch embed kernel / stride.
236
+ in_channels (`int`, defaults to 128): Input/output channels.
237
+ hidden_size (`int`, defaults to 768): Transformer width.
238
+ num_layers (`int`, defaults to 12): Number of `JLTBlock`s.
239
+ num_attention_heads (`int`, defaults to 12): Attention heads.
240
+ mlp_ratio (`float`, defaults to 4.0): SwiGLU expansion.
241
+ num_classes (`int`, defaults to 1000): ImageNet classes (plus a null CFG class).
242
+ model_type (`str`, *optional*): Training-name label stored in `config.json` only.
243
+ """
244
+
245
  _supports_gradient_checkpointing = True
246
  _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
247
  _no_split_modules = ["JLTBlock"]
 
368
  return_features: bool = False,
369
  feature_layers: Optional[List[int]] = None,
370
  ):
371
+ """Predict the clean sample from a noisy latent / image `sample` at JLT time `timestep`."""
372
  t = torch.as_tensor(timestep, device=sample.device)
373
  if t.ndim == 0:
374
  t = t.repeat(sample.shape[0])
JLT-H-1/model_index.json ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "JLTPipeline"
5
+ ],
6
+ "_diffusers_version": "0.39.0",
7
+ "transformer": [
8
+ "transformer_jlt",
9
+ "JLTTransformer2DModel"
10
+ ],
11
+ "scheduler": [
12
+ "scheduling_jlt",
13
+ "JLTScheduler"
14
+ ],
15
+ "vae": [
16
+ "diffusers",
17
+ "AutoencoderKLFlux2"
18
+ ],
19
+ "id2label": {
20
+ "0": "tench, Tinca tinca",
21
+ "1": "goldfish, Carassius auratus",
22
+ "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
23
+ "3": "tiger shark, Galeocerdo cuvieri",
24
+ "4": "hammerhead, hammerhead shark",
25
+ "5": "electric ray, crampfish, numbfish, torpedo",
26
+ "6": "stingray",
27
+ "7": "cock",
28
+ "8": "hen",
29
+ "9": "ostrich, Struthio camelus",
30
+ "10": "brambling, Fringilla montifringilla",
31
+ "11": "goldfinch, Carduelis carduelis",
32
+ "12": "house finch, linnet, Carpodacus mexicanus",
33
+ "13": "junco, snowbird",
34
+ "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
35
+ "15": "robin, American robin, Turdus migratorius",
36
+ "16": "bulbul",
37
+ "17": "jay",
38
+ "18": "magpie",
39
+ "19": "chickadee",
40
+ "20": "water ouzel, dipper",
41
+ "21": "kite",
42
+ "22": "bald eagle, American eagle, Haliaeetus leucocephalus",
43
+ "23": "vulture",
44
+ "24": "great grey owl, great gray owl, Strix nebulosa",
45
+ "25": "European fire salamander, Salamandra salamandra",
46
+ "26": "common newt, Triturus vulgaris",
47
+ "27": "eft",
48
+ "28": "spotted salamander, Ambystoma maculatum",
49
+ "29": "axolotl, mud puppy, Ambystoma mexicanum",
50
+ "30": "bullfrog, Rana catesbeiana",
51
+ "31": "tree frog, tree-frog",
52
+ "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
53
+ "33": "loggerhead, loggerhead turtle, Caretta caretta",
54
+ "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
55
+ "35": "mud turtle",
56
+ "36": "terrapin",
57
+ "37": "box turtle, box tortoise",
58
+ "38": "banded gecko",
59
+ "39": "common iguana, iguana, Iguana iguana",
60
+ "40": "American chameleon, anole, Anolis carolinensis",
61
+ "41": "whiptail, whiptail lizard",
62
+ "42": "agama",
63
+ "43": "frilled lizard, Chlamydosaurus kingi",
64
+ "44": "alligator lizard",
65
+ "45": "Gila monster, Heloderma suspectum",
66
+ "46": "green lizard, Lacerta viridis",
67
+ "47": "African chameleon, Chamaeleo chamaeleon",
68
+ "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
69
+ "49": "African crocodile, Nile crocodile, Crocodylus niloticus",
70
+ "50": "American alligator, Alligator mississipiensis",
71
+ "51": "triceratops",
72
+ "52": "thunder snake, worm snake, Carphophis amoenus",
73
+ "53": "ringneck snake, ring-necked snake, ring snake",
74
+ "54": "hognose snake, puff adder, sand viper",
75
+ "55": "green snake, grass snake",
76
+ "56": "king snake, kingsnake",
77
+ "57": "garter snake, grass snake",
78
+ "58": "water snake",
79
+ "59": "vine snake",
80
+ "60": "night snake, Hypsiglena torquata",
81
+ "61": "boa constrictor, Constrictor constrictor",
82
+ "62": "rock python, rock snake, Python sebae",
83
+ "63": "Indian cobra, Naja naja",
84
+ "64": "green mamba",
85
+ "65": "sea snake",
86
+ "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
87
+ "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
88
+ "68": "sidewinder, horned rattlesnake, Crotalus cerastes",
89
+ "69": "trilobite",
90
+ "70": "harvestman, daddy longlegs, Phalangium opilio",
91
+ "71": "scorpion",
92
+ "72": "black and gold garden spider, Argiope aurantia",
93
+ "73": "barn spider, Araneus cavaticus",
94
+ "74": "garden spider, Aranea diademata",
95
+ "75": "black widow, Latrodectus mactans",
96
+ "76": "tarantula",
97
+ "77": "wolf spider, hunting spider",
98
+ "78": "tick",
99
+ "79": "centipede",
100
+ "80": "black grouse",
101
+ "81": "ptarmigan",
102
+ "82": "ruffed grouse, partridge, Bonasa umbellus",
103
+ "83": "prairie chicken, prairie grouse, prairie fowl",
104
+ "84": "peacock",
105
+ "85": "quail",
106
+ "86": "partridge",
107
+ "87": "African grey, African gray, Psittacus erithacus",
108
+ "88": "macaw",
109
+ "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
110
+ "90": "lorikeet",
111
+ "91": "coucal",
112
+ "92": "bee eater",
113
+ "93": "hornbill",
114
+ "94": "hummingbird",
115
+ "95": "jacamar",
116
+ "96": "toucan",
117
+ "97": "drake",
118
+ "98": "red-breasted merganser, Mergus serrator",
119
+ "99": "goose",
120
+ "100": "black swan, Cygnus atratus",
121
+ "101": "tusker",
122
+ "102": "echidna, spiny anteater, anteater",
123
+ "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
124
+ "104": "wallaby, brush kangaroo",
125
+ "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
126
+ "106": "wombat",
127
+ "107": "jellyfish",
128
+ "108": "sea anemone, anemone",
129
+ "109": "brain coral",
130
+ "110": "flatworm, platyhelminth",
131
+ "111": "nematode, nematode worm, roundworm",
132
+ "112": "conch",
133
+ "113": "snail",
134
+ "114": "slug",
135
+ "115": "sea slug, nudibranch",
136
+ "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
137
+ "117": "chambered nautilus, pearly nautilus, nautilus",
138
+ "118": "Dungeness crab, Cancer magister",
139
+ "119": "rock crab, Cancer irroratus",
140
+ "120": "fiddler crab",
141
+ "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
142
+ "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
143
+ "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
144
+ "124": "crayfish, crawfish, crawdad, crawdaddy",
145
+ "125": "hermit crab",
146
+ "126": "isopod",
147
+ "127": "white stork, Ciconia ciconia",
148
+ "128": "black stork, Ciconia nigra",
149
+ "129": "spoonbill",
150
+ "130": "flamingo",
151
+ "131": "little blue heron, Egretta caerulea",
152
+ "132": "American egret, great white heron, Egretta albus",
153
+ "133": "bittern",
154
+ "134": "crane",
155
+ "135": "limpkin, Aramus pictus",
156
+ "136": "European gallinule, Porphyrio porphyrio",
157
+ "137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
158
+ "138": "bustard",
159
+ "139": "ruddy turnstone, Arenaria interpres",
160
+ "140": "red-backed sandpiper, dunlin, Erolia alpina",
161
+ "141": "redshank, Tringa totanus",
162
+ "142": "dowitcher",
163
+ "143": "oystercatcher, oyster catcher",
164
+ "144": "pelican",
165
+ "145": "king penguin, Aptenodytes patagonica",
166
+ "146": "albatross, mollymawk",
167
+ "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
168
+ "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
169
+ "149": "dugong, Dugong dugon",
170
+ "150": "sea lion",
171
+ "151": "Chihuahua",
172
+ "152": "Japanese spaniel",
173
+ "153": "Maltese dog, Maltese terrier, Maltese",
174
+ "154": "Pekinese, Pekingese, Peke",
175
+ "155": "Shih-Tzu",
176
+ "156": "Blenheim spaniel",
177
+ "157": "papillon",
178
+ "158": "toy terrier",
179
+ "159": "Rhodesian ridgeback",
180
+ "160": "Afghan hound, Afghan",
181
+ "161": "basset, basset hound",
182
+ "162": "beagle",
183
+ "163": "bloodhound, sleuthhound",
184
+ "164": "bluetick",
185
+ "165": "black-and-tan coonhound",
186
+ "166": "Walker hound, Walker foxhound",
187
+ "167": "English foxhound",
188
+ "168": "redbone",
189
+ "169": "borzoi, Russian wolfhound",
190
+ "170": "Irish wolfhound",
191
+ "171": "Italian greyhound",
192
+ "172": "whippet",
193
+ "173": "Ibizan hound, Ibizan Podenco",
194
+ "174": "Norwegian elkhound, elkhound",
195
+ "175": "otterhound, otter hound",
196
+ "176": "Saluki, gazelle hound",
197
+ "177": "Scottish deerhound, deerhound",
198
+ "178": "Weimaraner",
199
+ "179": "Staffordshire bullterrier, Staffordshire bull terrier",
200
+ "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
201
+ "181": "Bedlington terrier",
202
+ "182": "Border terrier",
203
+ "183": "Kerry blue terrier",
204
+ "184": "Irish terrier",
205
+ "185": "Norfolk terrier",
206
+ "186": "Norwich terrier",
207
+ "187": "Yorkshire terrier",
208
+ "188": "wire-haired fox terrier",
209
+ "189": "Lakeland terrier",
210
+ "190": "Sealyham terrier, Sealyham",
211
+ "191": "Airedale, Airedale terrier",
212
+ "192": "cairn, cairn terrier",
213
+ "193": "Australian terrier",
214
+ "194": "Dandie Dinmont, Dandie Dinmont terrier",
215
+ "195": "Boston bull, Boston terrier",
216
+ "196": "miniature schnauzer",
217
+ "197": "giant schnauzer",
218
+ "198": "standard schnauzer",
219
+ "199": "Scotch terrier, Scottish terrier, Scottie",
220
+ "200": "Tibetan terrier, chrysanthemum dog",
221
+ "201": "silky terrier, Sydney silky",
222
+ "202": "soft-coated wheaten terrier",
223
+ "203": "West Highland white terrier",
224
+ "204": "Lhasa, Lhasa apso",
225
+ "205": "flat-coated retriever",
226
+ "206": "curly-coated retriever",
227
+ "207": "golden retriever",
228
+ "208": "Labrador retriever",
229
+ "209": "Chesapeake Bay retriever",
230
+ "210": "German short-haired pointer",
231
+ "211": "vizsla, Hungarian pointer",
232
+ "212": "English setter",
233
+ "213": "Irish setter, red setter",
234
+ "214": "Gordon setter",
235
+ "215": "Brittany spaniel",
236
+ "216": "clumber, clumber spaniel",
237
+ "217": "English springer, English springer spaniel",
238
+ "218": "Welsh springer spaniel",
239
+ "219": "cocker spaniel, English cocker spaniel, cocker",
240
+ "220": "Sussex spaniel",
241
+ "221": "Irish water spaniel",
242
+ "222": "kuvasz",
243
+ "223": "schipperke",
244
+ "224": "groenendael",
245
+ "225": "malinois",
246
+ "226": "briard",
247
+ "227": "kelpie",
248
+ "228": "komondor",
249
+ "229": "Old English sheepdog, bobtail",
250
+ "230": "Shetland sheepdog, Shetland sheep dog, Shetland",
251
+ "231": "collie",
252
+ "232": "Border collie",
253
+ "233": "Bouvier des Flandres, Bouviers des Flandres",
254
+ "234": "Rottweiler",
255
+ "235": "German shepherd, German shepherd dog, German police dog, alsatian",
256
+ "236": "Doberman, Doberman pinscher",
257
+ "237": "miniature pinscher",
258
+ "238": "Greater Swiss Mountain dog",
259
+ "239": "Bernese mountain dog",
260
+ "240": "Appenzeller",
261
+ "241": "EntleBucher",
262
+ "242": "boxer",
263
+ "243": "bull mastiff",
264
+ "244": "Tibetan mastiff",
265
+ "245": "French bulldog",
266
+ "246": "Great Dane",
267
+ "247": "Saint Bernard, St Bernard",
268
+ "248": "Eskimo dog, husky",
269
+ "249": "malamute, malemute, Alaskan malamute",
270
+ "250": "Siberian husky",
271
+ "251": "dalmatian, coach dog, carriage dog",
272
+ "252": "affenpinscher, monkey pinscher, monkey dog",
273
+ "253": "basenji",
274
+ "254": "pug, pug-dog",
275
+ "255": "Leonberg",
276
+ "256": "Newfoundland, Newfoundland dog",
277
+ "257": "Great Pyrenees",
278
+ "258": "Samoyed, Samoyede",
279
+ "259": "Pomeranian",
280
+ "260": "chow, chow chow",
281
+ "261": "keeshond",
282
+ "262": "Brabancon griffon",
283
+ "263": "Pembroke, Pembroke Welsh corgi",
284
+ "264": "Cardigan, Cardigan Welsh corgi",
285
+ "265": "toy poodle",
286
+ "266": "miniature poodle",
287
+ "267": "standard poodle",
288
+ "268": "Mexican hairless",
289
+ "269": "timber wolf, grey wolf, gray wolf, Canis lupus",
290
+ "270": "white wolf, Arctic wolf, Canis lupus tundrarum",
291
+ "271": "red wolf, maned wolf, Canis rufus, Canis niger",
292
+ "272": "coyote, prairie wolf, brush wolf, Canis latrans",
293
+ "273": "dingo, warrigal, warragal, Canis dingo",
294
+ "274": "dhole, Cuon alpinus",
295
+ "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
296
+ "276": "hyena, hyaena",
297
+ "277": "red fox, Vulpes vulpes",
298
+ "278": "kit fox, Vulpes macrotis",
299
+ "279": "Arctic fox, white fox, Alopex lagopus",
300
+ "280": "grey fox, gray fox, Urocyon cinereoargenteus",
301
+ "281": "tabby, tabby cat",
302
+ "282": "tiger cat",
303
+ "283": "Persian cat",
304
+ "284": "Siamese cat, Siamese",
305
+ "285": "Egyptian cat",
306
+ "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
307
+ "287": "lynx, catamount",
308
+ "288": "leopard, Panthera pardus",
309
+ "289": "snow leopard, ounce, Panthera uncia",
310
+ "290": "jaguar, panther, Panthera onca, Felis onca",
311
+ "291": "lion, king of beasts, Panthera leo",
312
+ "292": "tiger, Panthera tigris",
313
+ "293": "cheetah, chetah, Acinonyx jubatus",
314
+ "294": "brown bear, bruin, Ursus arctos",
315
+ "295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
316
+ "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
317
+ "297": "sloth bear, Melursus ursinus, Ursus ursinus",
318
+ "298": "mongoose",
319
+ "299": "meerkat, mierkat",
320
+ "300": "tiger beetle",
321
+ "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
322
+ "302": "ground beetle, carabid beetle",
323
+ "303": "long-horned beetle, longicorn, longicorn beetle",
324
+ "304": "leaf beetle, chrysomelid",
325
+ "305": "dung beetle",
326
+ "306": "rhinoceros beetle",
327
+ "307": "weevil",
328
+ "308": "fly",
329
+ "309": "bee",
330
+ "310": "ant, emmet, pismire",
331
+ "311": "grasshopper, hopper",
332
+ "312": "cricket",
333
+ "313": "walking stick, walkingstick, stick insect",
334
+ "314": "cockroach, roach",
335
+ "315": "mantis, mantid",
336
+ "316": "cicada, cicala",
337
+ "317": "leafhopper",
338
+ "318": "lacewing, lacewing fly",
339
+ "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
340
+ "320": "damselfly",
341
+ "321": "admiral",
342
+ "322": "ringlet, ringlet butterfly",
343
+ "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
344
+ "324": "cabbage butterfly",
345
+ "325": "sulphur butterfly, sulfur butterfly",
346
+ "326": "lycaenid, lycaenid butterfly",
347
+ "327": "starfish, sea star",
348
+ "328": "sea urchin",
349
+ "329": "sea cucumber, holothurian",
350
+ "330": "wood rabbit, cottontail, cottontail rabbit",
351
+ "331": "hare",
352
+ "332": "Angora, Angora rabbit",
353
+ "333": "hamster",
354
+ "334": "porcupine, hedgehog",
355
+ "335": "fox squirrel, eastern fox squirrel, Sciurus niger",
356
+ "336": "marmot",
357
+ "337": "beaver",
358
+ "338": "guinea pig, Cavia cobaya",
359
+ "339": "sorrel",
360
+ "340": "zebra",
361
+ "341": "hog, pig, grunter, squealer, Sus scrofa",
362
+ "342": "wild boar, boar, Sus scrofa",
363
+ "343": "warthog",
364
+ "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
365
+ "345": "ox",
366
+ "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
367
+ "347": "bison",
368
+ "348": "ram, tup",
369
+ "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
370
+ "350": "ibex, Capra ibex",
371
+ "351": "hartebeest",
372
+ "352": "impala, Aepyceros melampus",
373
+ "353": "gazelle",
374
+ "354": "Arabian camel, dromedary, Camelus dromedarius",
375
+ "355": "llama",
376
+ "356": "weasel",
377
+ "357": "mink",
378
+ "358": "polecat, fitch, foulmart, foumart, Mustela putorius",
379
+ "359": "black-footed ferret, ferret, Mustela nigripes",
380
+ "360": "otter",
381
+ "361": "skunk, polecat, wood pussy",
382
+ "362": "badger",
383
+ "363": "armadillo",
384
+ "364": "three-toed sloth, ai, Bradypus tridactylus",
385
+ "365": "orangutan, orang, orangutang, Pongo pygmaeus",
386
+ "366": "gorilla, Gorilla gorilla",
387
+ "367": "chimpanzee, chimp, Pan troglodytes",
388
+ "368": "gibbon, Hylobates lar",
389
+ "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
390
+ "370": "guenon, guenon monkey",
391
+ "371": "patas, hussar monkey, Erythrocebus patas",
392
+ "372": "baboon",
393
+ "373": "macaque",
394
+ "374": "langur",
395
+ "375": "colobus, colobus monkey",
396
+ "376": "proboscis monkey, Nasalis larvatus",
397
+ "377": "marmoset",
398
+ "378": "capuchin, ringtail, Cebus capucinus",
399
+ "379": "howler monkey, howler",
400
+ "380": "titi, titi monkey",
401
+ "381": "spider monkey, Ateles geoffroyi",
402
+ "382": "squirrel monkey, Saimiri sciureus",
403
+ "383": "Madagascar cat, ring-tailed lemur, Lemur catta",
404
+ "384": "indri, indris, Indri indri, Indri brevicaudatus",
405
+ "385": "Indian elephant, Elephas maximus",
406
+ "386": "African elephant, Loxodonta africana",
407
+ "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
408
+ "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
409
+ "389": "barracouta, snoek",
410
+ "390": "eel",
411
+ "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
412
+ "392": "rock beauty, Holocanthus tricolor",
413
+ "393": "anemone fish",
414
+ "394": "sturgeon",
415
+ "395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
416
+ "396": "lionfish",
417
+ "397": "puffer, pufferfish, blowfish, globefish",
418
+ "398": "abacus",
419
+ "399": "abaya",
420
+ "400": "academic gown, academic robe, judge robe",
421
+ "401": "accordion, piano accordion, squeeze box",
422
+ "402": "acoustic guitar",
423
+ "403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
424
+ "404": "airliner",
425
+ "405": "airship, dirigible",
426
+ "406": "altar",
427
+ "407": "ambulance",
428
+ "408": "amphibian, amphibious vehicle",
429
+ "409": "analog clock",
430
+ "410": "apiary, bee house",
431
+ "411": "apron",
432
+ "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
433
+ "413": "assault rifle, assault gun",
434
+ "414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
435
+ "415": "bakery, bakeshop, bakehouse",
436
+ "416": "balance beam, beam",
437
+ "417": "balloon",
438
+ "418": "ballpoint, ballpoint pen, ballpen, Biro",
439
+ "419": "Band Aid",
440
+ "420": "banjo",
441
+ "421": "bannister, banister, balustrade, balusters, handrail",
442
+ "422": "barbell",
443
+ "423": "barber chair",
444
+ "424": "barbershop",
445
+ "425": "barn",
446
+ "426": "barometer",
447
+ "427": "barrel, cask",
448
+ "428": "barrow, garden cart, lawn cart, wheelbarrow",
449
+ "429": "baseball",
450
+ "430": "basketball",
451
+ "431": "bassinet",
452
+ "432": "bassoon",
453
+ "433": "bathing cap, swimming cap",
454
+ "434": "bath towel",
455
+ "435": "bathtub, bathing tub, bath, tub",
456
+ "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
457
+ "437": "beacon, lighthouse, beacon light, pharos",
458
+ "438": "beaker",
459
+ "439": "bearskin, busby, shako",
460
+ "440": "beer bottle",
461
+ "441": "beer glass",
462
+ "442": "bell cote, bell cot",
463
+ "443": "bib",
464
+ "444": "bicycle-built-for-two, tandem bicycle, tandem",
465
+ "445": "bikini, two-piece",
466
+ "446": "binder, ring-binder",
467
+ "447": "binoculars, field glasses, opera glasses",
468
+ "448": "birdhouse",
469
+ "449": "boathouse",
470
+ "450": "bobsled, bobsleigh, bob",
471
+ "451": "bolo tie, bolo, bola tie, bola",
472
+ "452": "bonnet, poke bonnet",
473
+ "453": "bookcase",
474
+ "454": "bookshop, bookstore, bookstall",
475
+ "455": "bottlecap",
476
+ "456": "bow",
477
+ "457": "bow tie, bow-tie, bowtie",
478
+ "458": "brass, memorial tablet, plaque",
479
+ "459": "brassiere, bra, bandeau",
480
+ "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
481
+ "461": "breastplate, aegis, egis",
482
+ "462": "broom",
483
+ "463": "bucket, pail",
484
+ "464": "buckle",
485
+ "465": "bulletproof vest",
486
+ "466": "bullet train, bullet",
487
+ "467": "butcher shop, meat market",
488
+ "468": "cab, hack, taxi, taxicab",
489
+ "469": "caldron, cauldron",
490
+ "470": "candle, taper, wax light",
491
+ "471": "cannon",
492
+ "472": "canoe",
493
+ "473": "can opener, tin opener",
494
+ "474": "cardigan",
495
+ "475": "car mirror",
496
+ "476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
497
+ "477": "carpenters kit, tool kit",
498
+ "478": "carton",
499
+ "479": "car wheel",
500
+ "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
501
+ "481": "cassette",
502
+ "482": "cassette player",
503
+ "483": "castle",
504
+ "484": "catamaran",
505
+ "485": "CD player",
506
+ "486": "cello, violoncello",
507
+ "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
508
+ "488": "chain",
509
+ "489": "chainlink fence",
510
+ "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
511
+ "491": "chain saw, chainsaw",
512
+ "492": "chest",
513
+ "493": "chiffonier, commode",
514
+ "494": "chime, bell, gong",
515
+ "495": "china cabinet, china closet",
516
+ "496": "Christmas stocking",
517
+ "497": "church, church building",
518
+ "498": "cinema, movie theater, movie theatre, movie house, picture palace",
519
+ "499": "cleaver, meat cleaver, chopper",
520
+ "500": "cliff dwelling",
521
+ "501": "cloak",
522
+ "502": "clog, geta, patten, sabot",
523
+ "503": "cocktail shaker",
524
+ "504": "coffee mug",
525
+ "505": "coffeepot",
526
+ "506": "coil, spiral, volute, whorl, helix",
527
+ "507": "combination lock",
528
+ "508": "computer keyboard, keypad",
529
+ "509": "confectionery, confectionary, candy store",
530
+ "510": "container ship, containership, container vessel",
531
+ "511": "convertible",
532
+ "512": "corkscrew, bottle screw",
533
+ "513": "cornet, horn, trumpet, trump",
534
+ "514": "cowboy boot",
535
+ "515": "cowboy hat, ten-gallon hat",
536
+ "516": "cradle",
537
+ "517": "crane",
538
+ "518": "crash helmet",
539
+ "519": "crate",
540
+ "520": "crib, cot",
541
+ "521": "Crock Pot",
542
+ "522": "croquet ball",
543
+ "523": "crutch",
544
+ "524": "cuirass",
545
+ "525": "dam, dike, dyke",
546
+ "526": "desk",
547
+ "527": "desktop computer",
548
+ "528": "dial telephone, dial phone",
549
+ "529": "diaper, nappy, napkin",
550
+ "530": "digital clock",
551
+ "531": "digital watch",
552
+ "532": "dining table, board",
553
+ "533": "dishrag, dishcloth",
554
+ "534": "dishwasher, dish washer, dishwashing machine",
555
+ "535": "disk brake, disc brake",
556
+ "536": "dock, dockage, docking facility",
557
+ "537": "dogsled, dog sled, dog sleigh",
558
+ "538": "dome",
559
+ "539": "doormat, welcome mat",
560
+ "540": "drilling platform, offshore rig",
561
+ "541": "drum, membranophone, tympan",
562
+ "542": "drumstick",
563
+ "543": "dumbbell",
564
+ "544": "Dutch oven",
565
+ "545": "electric fan, blower",
566
+ "546": "electric guitar",
567
+ "547": "electric locomotive",
568
+ "548": "entertainment center",
569
+ "549": "envelope",
570
+ "550": "espresso maker",
571
+ "551": "face powder",
572
+ "552": "feather boa, boa",
573
+ "553": "file, file cabinet, filing cabinet",
574
+ "554": "fireboat",
575
+ "555": "fire engine, fire truck",
576
+ "556": "fire screen, fireguard",
577
+ "557": "flagpole, flagstaff",
578
+ "558": "flute, transverse flute",
579
+ "559": "folding chair",
580
+ "560": "football helmet",
581
+ "561": "forklift",
582
+ "562": "fountain",
583
+ "563": "fountain pen",
584
+ "564": "four-poster",
585
+ "565": "freight car",
586
+ "566": "French horn, horn",
587
+ "567": "frying pan, frypan, skillet",
588
+ "568": "fur coat",
589
+ "569": "garbage truck, dustcart",
590
+ "570": "gasmask, respirator, gas helmet",
591
+ "571": "gas pump, gasoline pump, petrol pump, island dispenser",
592
+ "572": "goblet",
593
+ "573": "go-kart",
594
+ "574": "golf ball",
595
+ "575": "golfcart, golf cart",
596
+ "576": "gondola",
597
+ "577": "gong, tam-tam",
598
+ "578": "gown",
599
+ "579": "grand piano, grand",
600
+ "580": "greenhouse, nursery, glasshouse",
601
+ "581": "grille, radiator grille",
602
+ "582": "grocery store, grocery, food market, market",
603
+ "583": "guillotine",
604
+ "584": "hair slide",
605
+ "585": "hair spray",
606
+ "586": "half track",
607
+ "587": "hammer",
608
+ "588": "hamper",
609
+ "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
610
+ "590": "hand-held computer, hand-held microcomputer",
611
+ "591": "handkerchief, hankie, hanky, hankey",
612
+ "592": "hard disc, hard disk, fixed disk",
613
+ "593": "harmonica, mouth organ, harp, mouth harp",
614
+ "594": "harp",
615
+ "595": "harvester, reaper",
616
+ "596": "hatchet",
617
+ "597": "holster",
618
+ "598": "home theater, home theatre",
619
+ "599": "honeycomb",
620
+ "600": "hook, claw",
621
+ "601": "hoopskirt, crinoline",
622
+ "602": "horizontal bar, high bar",
623
+ "603": "horse cart, horse-cart",
624
+ "604": "hourglass",
625
+ "605": "iPod",
626
+ "606": "iron, smoothing iron",
627
+ "607": "jack-o-lantern",
628
+ "608": "jean, blue jean, denim",
629
+ "609": "jeep, landrover",
630
+ "610": "jersey, T-shirt, tee shirt",
631
+ "611": "jigsaw puzzle",
632
+ "612": "jinrikisha, ricksha, rickshaw",
633
+ "613": "joystick",
634
+ "614": "kimono",
635
+ "615": "knee pad",
636
+ "616": "knot",
637
+ "617": "lab coat, laboratory coat",
638
+ "618": "ladle",
639
+ "619": "lampshade, lamp shade",
640
+ "620": "laptop, laptop computer",
641
+ "621": "lawn mower, mower",
642
+ "622": "lens cap, lens cover",
643
+ "623": "letter opener, paper knife, paperknife",
644
+ "624": "library",
645
+ "625": "lifeboat",
646
+ "626": "lighter, light, igniter, ignitor",
647
+ "627": "limousine, limo",
648
+ "628": "liner, ocean liner",
649
+ "629": "lipstick, lip rouge",
650
+ "630": "Loafer",
651
+ "631": "lotion",
652
+ "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
653
+ "633": "loupe, jewelers loupe",
654
+ "634": "lumbermill, sawmill",
655
+ "635": "magnetic compass",
656
+ "636": "mailbag, postbag",
657
+ "637": "mailbox, letter box",
658
+ "638": "maillot",
659
+ "639": "maillot, tank suit",
660
+ "640": "manhole cover",
661
+ "641": "maraca",
662
+ "642": "marimba, xylophone",
663
+ "643": "mask",
664
+ "644": "matchstick",
665
+ "645": "maypole",
666
+ "646": "maze, labyrinth",
667
+ "647": "measuring cup",
668
+ "648": "medicine chest, medicine cabinet",
669
+ "649": "megalith, megalithic structure",
670
+ "650": "microphone, mike",
671
+ "651": "microwave, microwave oven",
672
+ "652": "military uniform",
673
+ "653": "milk can",
674
+ "654": "minibus",
675
+ "655": "miniskirt, mini",
676
+ "656": "minivan",
677
+ "657": "missile",
678
+ "658": "mitten",
679
+ "659": "mixing bowl",
680
+ "660": "mobile home, manufactured home",
681
+ "661": "Model T",
682
+ "662": "modem",
683
+ "663": "monastery",
684
+ "664": "monitor",
685
+ "665": "moped",
686
+ "666": "mortar",
687
+ "667": "mortarboard",
688
+ "668": "mosque",
689
+ "669": "mosquito net",
690
+ "670": "motor scooter, scooter",
691
+ "671": "mountain bike, all-terrain bike, off-roader",
692
+ "672": "mountain tent",
693
+ "673": "mouse, computer mouse",
694
+ "674": "mousetrap",
695
+ "675": "moving van",
696
+ "676": "muzzle",
697
+ "677": "nail",
698
+ "678": "neck brace",
699
+ "679": "necklace",
700
+ "680": "nipple",
701
+ "681": "notebook, notebook computer",
702
+ "682": "obelisk",
703
+ "683": "oboe, hautboy, hautbois",
704
+ "684": "ocarina, sweet potato",
705
+ "685": "odometer, hodometer, mileometer, milometer",
706
+ "686": "oil filter",
707
+ "687": "organ, pipe organ",
708
+ "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
709
+ "689": "overskirt",
710
+ "690": "oxcart",
711
+ "691": "oxygen mask",
712
+ "692": "packet",
713
+ "693": "paddle, boat paddle",
714
+ "694": "paddlewheel, paddle wheel",
715
+ "695": "padlock",
716
+ "696": "paintbrush",
717
+ "697": "pajama, pyjama, pjs, jammies",
718
+ "698": "palace",
719
+ "699": "panpipe, pandean pipe, syrinx",
720
+ "700": "paper towel",
721
+ "701": "parachute, chute",
722
+ "702": "parallel bars, bars",
723
+ "703": "park bench",
724
+ "704": "parking meter",
725
+ "705": "passenger car, coach, carriage",
726
+ "706": "patio, terrace",
727
+ "707": "pay-phone, pay-station",
728
+ "708": "pedestal, plinth, footstall",
729
+ "709": "pencil box, pencil case",
730
+ "710": "pencil sharpener",
731
+ "711": "perfume, essence",
732
+ "712": "Petri dish",
733
+ "713": "photocopier",
734
+ "714": "pick, plectrum, plectron",
735
+ "715": "pickelhaube",
736
+ "716": "picket fence, paling",
737
+ "717": "pickup, pickup truck",
738
+ "718": "pier",
739
+ "719": "piggy bank, penny bank",
740
+ "720": "pill bottle",
741
+ "721": "pillow",
742
+ "722": "ping-pong ball",
743
+ "723": "pinwheel",
744
+ "724": "pirate, pirate ship",
745
+ "725": "pitcher, ewer",
746
+ "726": "plane, carpenters plane, woodworking plane",
747
+ "727": "planetarium",
748
+ "728": "plastic bag",
749
+ "729": "plate rack",
750
+ "730": "plow, plough",
751
+ "731": "plunger, plumbers helper",
752
+ "732": "Polaroid camera, Polaroid Land camera",
753
+ "733": "pole",
754
+ "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
755
+ "735": "poncho",
756
+ "736": "pool table, billiard table, snooker table",
757
+ "737": "pop bottle, soda bottle",
758
+ "738": "pot, flowerpot",
759
+ "739": "potters wheel",
760
+ "740": "power drill",
761
+ "741": "prayer rug, prayer mat",
762
+ "742": "printer",
763
+ "743": "prison, prison house",
764
+ "744": "projectile, missile",
765
+ "745": "projector",
766
+ "746": "puck, hockey puck",
767
+ "747": "punching bag, punch bag, punching ball, punchball",
768
+ "748": "purse",
769
+ "749": "quill, quill pen",
770
+ "750": "quilt, comforter, comfort, puff",
771
+ "751": "racer, race car, racing car",
772
+ "752": "racket, racquet",
773
+ "753": "radiator",
774
+ "754": "radio, wireless",
775
+ "755": "radio telescope, radio reflector",
776
+ "756": "rain barrel",
777
+ "757": "recreational vehicle, RV, R.V.",
778
+ "758": "reel",
779
+ "759": "reflex camera",
780
+ "760": "refrigerator, icebox",
781
+ "761": "remote control, remote",
782
+ "762": "restaurant, eating house, eating place, eatery",
783
+ "763": "revolver, six-gun, six-shooter",
784
+ "764": "rifle",
785
+ "765": "rocking chair, rocker",
786
+ "766": "rotisserie",
787
+ "767": "rubber eraser, rubber, pencil eraser",
788
+ "768": "rugby ball",
789
+ "769": "rule, ruler",
790
+ "770": "running shoe",
791
+ "771": "safe",
792
+ "772": "safety pin",
793
+ "773": "saltshaker, salt shaker",
794
+ "774": "sandal",
795
+ "775": "sarong",
796
+ "776": "sax, saxophone",
797
+ "777": "scabbard",
798
+ "778": "scale, weighing machine",
799
+ "779": "school bus",
800
+ "780": "schooner",
801
+ "781": "scoreboard",
802
+ "782": "screen, CRT screen",
803
+ "783": "screw",
804
+ "784": "screwdriver",
805
+ "785": "seat belt, seatbelt",
806
+ "786": "sewing machine",
807
+ "787": "shield, buckler",
808
+ "788": "shoe shop, shoe-shop, shoe store",
809
+ "789": "shoji",
810
+ "790": "shopping basket",
811
+ "791": "shopping cart",
812
+ "792": "shovel",
813
+ "793": "shower cap",
814
+ "794": "shower curtain",
815
+ "795": "ski",
816
+ "796": "ski mask",
817
+ "797": "sleeping bag",
818
+ "798": "slide rule, slipstick",
819
+ "799": "sliding door",
820
+ "800": "slot, one-armed bandit",
821
+ "801": "snorkel",
822
+ "802": "snowmobile",
823
+ "803": "snowplow, snowplough",
824
+ "804": "soap dispenser",
825
+ "805": "soccer ball",
826
+ "806": "sock",
827
+ "807": "solar dish, solar collector, solar furnace",
828
+ "808": "sombrero",
829
+ "809": "soup bowl",
830
+ "810": "space bar",
831
+ "811": "space heater",
832
+ "812": "space shuttle",
833
+ "813": "spatula",
834
+ "814": "speedboat",
835
+ "815": "spider web, spiders web",
836
+ "816": "spindle",
837
+ "817": "sports car, sport car",
838
+ "818": "spotlight, spot",
839
+ "819": "stage",
840
+ "820": "steam locomotive",
841
+ "821": "steel arch bridge",
842
+ "822": "steel drum",
843
+ "823": "stethoscope",
844
+ "824": "stole",
845
+ "825": "stone wall",
846
+ "826": "stopwatch, stop watch",
847
+ "827": "stove",
848
+ "828": "strainer",
849
+ "829": "streetcar, tram, tramcar, trolley, trolley car",
850
+ "830": "stretcher",
851
+ "831": "studio couch, day bed",
852
+ "832": "stupa, tope",
853
+ "833": "submarine, pigboat, sub, U-boat",
854
+ "834": "suit, suit of clothes",
855
+ "835": "sundial",
856
+ "836": "sunglass",
857
+ "837": "sunglasses, dark glasses, shades",
858
+ "838": "sunscreen, sunblock, sun blocker",
859
+ "839": "suspension bridge",
860
+ "840": "swab, swob, mop",
861
+ "841": "sweatshirt",
862
+ "842": "swimming trunks, bathing trunks",
863
+ "843": "swing",
864
+ "844": "switch, electric switch, electrical switch",
865
+ "845": "syringe",
866
+ "846": "table lamp",
867
+ "847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
868
+ "848": "tape player",
869
+ "849": "teapot",
870
+ "850": "teddy, teddy bear",
871
+ "851": "television, television system",
872
+ "852": "tennis ball",
873
+ "853": "thatch, thatched roof",
874
+ "854": "theater curtain, theatre curtain",
875
+ "855": "thimble",
876
+ "856": "thresher, thrasher, threshing machine",
877
+ "857": "throne",
878
+ "858": "tile roof",
879
+ "859": "toaster",
880
+ "860": "tobacco shop, tobacconist shop, tobacconist",
881
+ "861": "toilet seat",
882
+ "862": "torch",
883
+ "863": "totem pole",
884
+ "864": "tow truck, tow car, wrecker",
885
+ "865": "toyshop",
886
+ "866": "tractor",
887
+ "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
888
+ "868": "tray",
889
+ "869": "trench coat",
890
+ "870": "tricycle, trike, velocipede",
891
+ "871": "trimaran",
892
+ "872": "tripod",
893
+ "873": "triumphal arch",
894
+ "874": "trolleybus, trolley coach, trackless trolley",
895
+ "875": "trombone",
896
+ "876": "tub, vat",
897
+ "877": "turnstile",
898
+ "878": "typewriter keyboard",
899
+ "879": "umbrella",
900
+ "880": "unicycle, monocycle",
901
+ "881": "upright, upright piano",
902
+ "882": "vacuum, vacuum cleaner",
903
+ "883": "vase",
904
+ "884": "vault",
905
+ "885": "velvet",
906
+ "886": "vending machine",
907
+ "887": "vestment",
908
+ "888": "viaduct",
909
+ "889": "violin, fiddle",
910
+ "890": "volleyball",
911
+ "891": "waffle iron",
912
+ "892": "wall clock",
913
+ "893": "wallet, billfold, notecase, pocketbook",
914
+ "894": "wardrobe, closet, press",
915
+ "895": "warplane, military plane",
916
+ "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
917
+ "897": "washer, automatic washer, washing machine",
918
+ "898": "water bottle",
919
+ "899": "water jug",
920
+ "900": "water tower",
921
+ "901": "whiskey jug",
922
+ "902": "whistle",
923
+ "903": "wig",
924
+ "904": "window screen",
925
+ "905": "window shade",
926
+ "906": "Windsor tie",
927
+ "907": "wine bottle",
928
+ "908": "wing",
929
+ "909": "wok",
930
+ "910": "wooden spoon",
931
+ "911": "wool, woolen, woollen",
932
+ "912": "worm fence, snake fence, snake-rail fence, Virginia fence",
933
+ "913": "wreck",
934
+ "914": "yawl",
935
+ "915": "yurt",
936
+ "916": "web site, website, internet site, site",
937
+ "917": "comic book",
938
+ "918": "crossword puzzle, crossword",
939
+ "919": "street sign",
940
+ "920": "traffic light, traffic signal, stoplight",
941
+ "921": "book jacket, dust cover, dust jacket, dust wrapper",
942
+ "922": "menu",
943
+ "923": "plate",
944
+ "924": "guacamole",
945
+ "925": "consomme",
946
+ "926": "hot pot, hotpot",
947
+ "927": "trifle",
948
+ "928": "ice cream, icecream",
949
+ "929": "ice lolly, lolly, lollipop, popsicle",
950
+ "930": "French loaf",
951
+ "931": "bagel, beigel",
952
+ "932": "pretzel",
953
+ "933": "cheeseburger",
954
+ "934": "hotdog, hot dog, red hot",
955
+ "935": "mashed potato",
956
+ "936": "head cabbage",
957
+ "937": "broccoli",
958
+ "938": "cauliflower",
959
+ "939": "zucchini, courgette",
960
+ "940": "spaghetti squash",
961
+ "941": "acorn squash",
962
+ "942": "butternut squash",
963
+ "943": "cucumber, cuke",
964
+ "944": "artichoke, globe artichoke",
965
+ "945": "bell pepper",
966
+ "946": "cardoon",
967
+ "947": "mushroom",
968
+ "948": "Granny Smith",
969
+ "949": "strawberry",
970
+ "950": "orange",
971
+ "951": "lemon",
972
+ "952": "fig",
973
+ "953": "pineapple, ananas",
974
+ "954": "banana",
975
+ "955": "jackfruit, jak, jack",
976
+ "956": "custard apple",
977
+ "957": "pomegranate",
978
+ "958": "hay",
979
+ "959": "carbonara",
980
+ "960": "chocolate sauce, chocolate syrup",
981
+ "961": "dough",
982
+ "962": "meat loaf, meatloaf",
983
+ "963": "pizza, pizza pie",
984
+ "964": "potpie",
985
+ "965": "burrito",
986
+ "966": "red wine",
987
+ "967": "espresso",
988
+ "968": "cup",
989
+ "969": "eggnog",
990
+ "970": "alp",
991
+ "971": "bubble",
992
+ "972": "cliff, drop, drop-off",
993
+ "973": "coral reef",
994
+ "974": "geyser",
995
+ "975": "lakeside, lakeshore",
996
+ "976": "promontory, headland, head, foreland",
997
+ "977": "sandbar, sand bar",
998
+ "978": "seashore, coast, seacoast, sea-coast",
999
+ "979": "valley, vale",
1000
+ "980": "volcano",
1001
+ "981": "ballplayer, baseball player",
1002
+ "982": "groom, bridegroom",
1003
+ "983": "scuba diver",
1004
+ "984": "rapeseed",
1005
+ "985": "daisy",
1006
+ "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
1007
+ "987": "corn",
1008
+ "988": "acorn",
1009
+ "989": "hip, rose hip, rosehip",
1010
+ "990": "buckeye, horse chestnut, conker",
1011
+ "991": "coral fungus",
1012
+ "992": "agaric",
1013
+ "993": "gyromitra",
1014
+ "994": "stinkhorn, carrion fungus",
1015
+ "995": "earthstar",
1016
+ "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
1017
+ "997": "bolete",
1018
+ "998": "ear, spike, capitulum",
1019
+ "999": "toilet tissue, toilet paper, bathroom tissue"
1020
+ }
1021
+ }
JLT-H-1/pipeline.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: JLTPipeline.
2
+ Load with native Hugging Face diffusers and trust_remote_code=True.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import importlib
8
+ import importlib.util
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Dict, List, Optional, Tuple, Union
13
+
14
+ import torch
15
+ from diffusers import AutoencoderKLFlux2
16
+ from diffusers.image_processor import VaeImageProcessor
17
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
18
+ from diffusers.utils.torch_utils import randn_tensor
19
+
20
+
21
+ def _load_jlt_scheduler_module():
22
+ module_path = Path(__file__).resolve().parent / "scheduler" / "scheduling_jlt.py"
23
+ spec = importlib.util.spec_from_file_location("scheduling_jlt", module_path)
24
+ module = importlib.util.module_from_spec(spec)
25
+ spec.loader.exec_module(module)
26
+ return module
27
+
28
+
29
+ JLTScheduler = _load_jlt_scheduler_module().JLTScheduler
30
+
31
+
32
+ def _unpatchify_latents(latents: torch.Tensor) -> torch.Tensor:
33
+ batch_size, num_channels_latents, height, width = latents.shape
34
+ latents = latents.reshape(batch_size, num_channels_latents // (2 * 2), 2, 2, height, width)
35
+ latents = latents.permute(0, 1, 4, 2, 5, 3)
36
+ return latents.reshape(batch_size, num_channels_latents // (2 * 2), height * 2, width * 2)
37
+
38
+
39
+ def _flux2_bn_stats(vae: AutoencoderKLFlux2, ref: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
40
+ mean = vae.bn.running_mean.view(1, -1, 1, 1).to(ref.device, ref.dtype)
41
+ std = torch.sqrt(
42
+ vae.bn.running_var.view(1, -1, 1, 1).to(ref.device, ref.dtype) + vae.config.batch_norm_eps
43
+ )
44
+ return mean, std
45
+
46
+
47
+ @torch.no_grad()
48
+ def decode_flux2_latents(vae: AutoencoderKLFlux2, latents: torch.Tensor) -> torch.Tensor:
49
+ vae_param = next(vae.parameters())
50
+ latents = latents.to(device=vae_param.device, dtype=torch.float32)
51
+ mean, std = _flux2_bn_stats(vae, latents)
52
+ latents = latents * std + mean
53
+ latents = _unpatchify_latents(latents)
54
+ return vae.decode(latents.to(vae_param.dtype), return_dict=False)[0].float()
55
+
56
+
57
+ def _new_jlt_scheduler(solver: str = "heun") -> JLTScheduler:
58
+ if solver not in {"heun", "euler"}:
59
+ raise ValueError("solver must be one of: 'heun', 'euler'.")
60
+ return JLTScheduler(solver=solver)
61
+
62
+
63
+ def _solver_from_scheduler(scheduler) -> str:
64
+ solver = getattr(getattr(scheduler, "config", None), "solver", None)
65
+ if solver in {"heun", "euler"}:
66
+ return solver
67
+ return "heun"
68
+
69
+
70
+ class JLTPipeline(DiffusionPipeline):
71
+ r"""
72
+ Class-conditional JLT sampler.
73
+
74
+ Starts from unit Gaussian noise in FLUX.2 latent space (`noise_scale=1.0`) at the
75
+ trained 256Γ—256 resolution, integrates `JLTScheduler` (Heun, last step Euler),
76
+ applies interval CFG in velocity space, and decodes FLUX.2 latents when a VAE is attached.
77
+ """
78
+
79
+ model_cpu_offload_seq = "transformer->vae"
80
+ _optional_components = ["vae"]
81
+
82
+ def __init__(
83
+ self,
84
+ transformer,
85
+ scheduler,
86
+ vae=None,
87
+ id2label=None,
88
+ prediction_type="sample",
89
+ t_eps=5e-2,
90
+ solver="heun",
91
+ ):
92
+ super().__init__()
93
+ if scheduler is None or isinstance(scheduler, list):
94
+ scheduler = _new_jlt_scheduler(solver)
95
+ self.register_modules(
96
+ transformer=transformer,
97
+ scheduler=scheduler,
98
+ vae=vae,
99
+ )
100
+ self.image_processor = VaeImageProcessor(vae_scale_factor=1)
101
+ self.prediction_type = prediction_type
102
+ self.t_eps = t_eps
103
+ self.solver = _solver_from_scheduler(scheduler)
104
+ self._id2label = self._normalize_id2label(id2label)
105
+ self.labels = self._build_label2id(self._id2label)
106
+ self._labels_loaded_from_model_index = bool(self._id2label)
107
+
108
+ @classmethod
109
+ def from_pretrained(cls, pretrained_model_name_or_path=None, subfolder=None, **kwargs):
110
+ repo_root = Path(__file__).resolve().parent
111
+
112
+ if pretrained_model_name_or_path in (None, "", "."):
113
+ variant = repo_root
114
+ else:
115
+ variant = Path(pretrained_model_name_or_path)
116
+ if not variant.is_absolute():
117
+ candidate = (Path.cwd() / variant).resolve()
118
+ variant = candidate if candidate.exists() else (repo_root / variant).resolve()
119
+ if subfolder:
120
+ variant = variant / subfolder
121
+
122
+ model_kwargs = dict(kwargs)
123
+ inserted: List[str] = []
124
+
125
+ def _load_transformer():
126
+ comp_dir = None
127
+ candidate = variant / "transformer"
128
+ if (candidate / "transformer_jlt.py").exists() and (candidate / "config.json").exists():
129
+ comp_dir = candidate
130
+ else:
131
+ comp_dir = None
132
+ if comp_dir is None:
133
+ return None
134
+ module_path = comp_dir / "transformer_jlt.py"
135
+ if not module_path.exists() or not (comp_dir / "config.json").exists():
136
+ return None
137
+
138
+ comp_path = str(comp_dir)
139
+ if comp_path not in sys.path:
140
+ sys.path.insert(0, comp_path)
141
+ inserted.append(comp_path)
142
+
143
+ module = importlib.import_module("transformer_jlt")
144
+ transformer_cls = getattr(module, "JLTTransformer2DModel")
145
+ return transformer_cls.from_pretrained(str(comp_dir), **model_kwargs)
146
+
147
+ def _load_scheduler():
148
+ scheduler_dir = variant / "scheduler"
149
+ config_path = scheduler_dir / "scheduler_config.json"
150
+ if not config_path.exists():
151
+ return _new_jlt_scheduler("heun")
152
+
153
+ scheduler_entry = None
154
+ model_index_path = variant / "model_index.json"
155
+ if model_index_path.exists():
156
+ scheduler_entry = json.loads(model_index_path.read_text(encoding="utf-8")).get("scheduler")
157
+
158
+ if scheduler_entry is None:
159
+ class_name = json.loads(config_path.read_text(encoding="utf-8")).get("_class_name")
160
+ scheduler_entry = ["diffusers", class_name]
161
+
162
+ module_name, class_name = scheduler_entry
163
+ if module_name == "diffusers":
164
+ import diffusers.schedulers as schedulers_pkg
165
+
166
+ scheduler_cls = getattr(schedulers_pkg, class_name)
167
+ return scheduler_cls.from_pretrained(str(scheduler_dir), **model_kwargs)
168
+
169
+ comp_path = str(scheduler_dir)
170
+ if comp_path not in sys.path:
171
+ sys.path.insert(0, comp_path)
172
+ inserted.append(comp_path)
173
+ module = importlib.import_module(module_name)
174
+ scheduler_cls = getattr(module, class_name)
175
+ return scheduler_cls.from_pretrained(str(scheduler_dir), **model_kwargs)
176
+
177
+ def _load_vae():
178
+ vae_dir = variant / "vae"
179
+ if vae_dir.exists() and (vae_dir / "config.json").exists():
180
+ return AutoencoderKLFlux2.from_pretrained(str(vae_dir), **model_kwargs)
181
+ return None
182
+
183
+ try:
184
+ transformer = _load_transformer()
185
+ if transformer is None:
186
+ raise ValueError(f"No loadable transformer found under {variant}")
187
+
188
+ scheduler = _load_scheduler()
189
+ vae = _load_vae()
190
+ id2label = cls._read_id2label_from_model_index(str(variant))
191
+ solver = _solver_from_scheduler(scheduler)
192
+ pipe = cls(
193
+ transformer=transformer,
194
+ scheduler=scheduler,
195
+ vae=vae,
196
+ id2label=id2label or None,
197
+ solver=solver,
198
+ )
199
+ if hasattr(pipe, "register_to_config"):
200
+ pipe.register_to_config(_name_or_path=str(variant))
201
+ return pipe
202
+ finally:
203
+ for comp_path in inserted:
204
+ if comp_path in sys.path:
205
+ sys.path.remove(comp_path)
206
+
207
+ @staticmethod
208
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
209
+ if not id2label:
210
+ return {}
211
+ return {int(key): value for key, value in id2label.items()}
212
+
213
+ @staticmethod
214
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
215
+ if not variant_path:
216
+ return {}
217
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
218
+ if not model_index_path.exists():
219
+ return {}
220
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
221
+ id2label = raw.get("id2label")
222
+ if not isinstance(id2label, dict):
223
+ return {}
224
+ return {int(key): value for key, value in id2label.items()}
225
+
226
+ @staticmethod
227
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
228
+ label2id: Dict[str, int] = {}
229
+ for class_id, value in id2label.items():
230
+ for synonym in value.split(","):
231
+ synonym = synonym.strip()
232
+ if synonym:
233
+ label2id[synonym] = int(class_id)
234
+ return dict(sorted(label2id.items()))
235
+
236
+ def _ensure_labels_loaded(self) -> None:
237
+ if self._labels_loaded_from_model_index:
238
+ return
239
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
240
+ if loaded:
241
+ self._id2label = loaded
242
+ self.labels = self._build_label2id(self._id2label)
243
+ self._labels_loaded_from_model_index = True
244
+
245
+ @property
246
+ def id2label(self) -> Dict[int, str]:
247
+ self._ensure_labels_loaded()
248
+ return self._id2label
249
+
250
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
251
+ self._ensure_labels_loaded()
252
+ if not self.labels:
253
+ raise ValueError("No labels loaded. Ensure `id2label` exists in model_index.json.")
254
+ if isinstance(label, str):
255
+ label = [label]
256
+ missing = [item for item in label if item not in self.labels]
257
+ if missing:
258
+ preview = ", ".join(list(self.labels.keys())[:8])
259
+ raise ValueError(f"Unknown label(s): {missing}. Examples: {preview}, ...")
260
+ return [self.labels[item] for item in label]
261
+
262
+ def _normalize_class_labels(self, class_labels: Union[int, str, List[Union[int, str]]]) -> List[int]:
263
+ if isinstance(class_labels, int):
264
+ return [class_labels]
265
+ if isinstance(class_labels, str):
266
+ return self.get_label_ids(class_labels)
267
+ if class_labels and isinstance(class_labels[0], str):
268
+ return self.get_label_ids(class_labels)
269
+ return list(class_labels)
270
+
271
+ def _predict_velocity_at_t(
272
+ self,
273
+ z_value: torch.Tensor,
274
+ t_jlt: Union[float, torch.Tensor],
275
+ class_labels: torch.Tensor,
276
+ class_null: torch.Tensor,
277
+ do_classifier_free_guidance: bool,
278
+ guidance_scale: float,
279
+ guidance_interval_min: float,
280
+ guidance_interval_max: float,
281
+ ) -> torch.Tensor:
282
+ t_jlt = torch.as_tensor(t_jlt, device=z_value.device, dtype=z_value.dtype)
283
+ if t_jlt.ndim == 0:
284
+ t_jlt = t_jlt.reshape(1)
285
+
286
+ if do_classifier_free_guidance:
287
+ z_in = torch.cat([z_value, z_value], dim=0)
288
+ labels = torch.cat([class_labels, class_null], dim=0)
289
+ else:
290
+ z_in = z_value
291
+ labels = class_labels
292
+
293
+ t_batch = t_jlt.flatten().expand(z_in.shape[0]).to(dtype=self.transformer.dtype)
294
+ model_out = self.transformer(
295
+ z_in.to(self.transformer.dtype),
296
+ timestep=t_batch,
297
+ class_labels=labels,
298
+ ).sample
299
+
300
+ # velocity in fp32; clamp the 1 / (1 - t) denominator at JLT's `t_eps` (0.05).
301
+ v = self.scheduler.velocity_from_prediction(
302
+ z_in.float(),
303
+ model_out.float(),
304
+ t_jlt,
305
+ prediction_type=self.prediction_type,
306
+ t_eps=self.t_eps,
307
+ )
308
+
309
+ if not do_classifier_free_guidance:
310
+ return v
311
+
312
+ v_cond, v_uncond = v.chunk(2, dim=0)
313
+ interval_mask = t_jlt < guidance_interval_max
314
+ if guidance_interval_min != 0.0:
315
+ interval_mask = interval_mask & (t_jlt > guidance_interval_min)
316
+ scale = torch.where(
317
+ interval_mask,
318
+ torch.tensor(guidance_scale, device=z_value.device, dtype=torch.float32),
319
+ torch.tensor(1.0, device=z_value.device, dtype=torch.float32),
320
+ )
321
+ return v_uncond + scale * (v_cond - v_uncond)
322
+
323
+ def _run_sampler(
324
+ self,
325
+ latents: torch.Tensor,
326
+ class_labels: torch.Tensor,
327
+ class_null: torch.Tensor,
328
+ num_inference_steps: int,
329
+ do_classifier_free_guidance: bool,
330
+ guidance_scale: float,
331
+ guidance_interval_min: float,
332
+ guidance_interval_max: float,
333
+ ) -> torch.Tensor:
334
+ self.scheduler.set_timesteps(num_inference_steps, device=latents.device)
335
+ for t_jlt in self.progress_bar(self.scheduler.timesteps):
336
+ velocity = self._predict_velocity_at_t(
337
+ latents,
338
+ t_jlt,
339
+ class_labels,
340
+ class_null,
341
+ do_classifier_free_guidance,
342
+ guidance_scale,
343
+ guidance_interval_min,
344
+ guidance_interval_max,
345
+ )
346
+ latents = self.scheduler.step(
347
+ velocity,
348
+ t_jlt,
349
+ latents,
350
+ prediction_type="velocity",
351
+ t_eps=self.t_eps,
352
+ ).prev_sample
353
+ return latents
354
+
355
+ @torch.no_grad()
356
+ def __call__(
357
+ self,
358
+ class_labels: Union[int, str, List[Union[int, str]]],
359
+ guidance_scale: Optional[float] = None,
360
+ guidance_interval_min: float = 0.1,
361
+ guidance_interval_max: float = 1.0,
362
+ noise_scale: Optional[float] = None,
363
+ t_eps: Optional[float] = None,
364
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
365
+ num_inference_steps: int = 50,
366
+ output_type: Optional[str] = "pil",
367
+ return_dict: bool = True,
368
+ ) -> Union[ImagePipelineOutput, Tuple]:
369
+ r"""
370
+ The call function to the pipeline for generation.
371
+
372
+ Args:
373
+ class_labels (`int`, `str`, or list):
374
+ ImageNet class id(s) or English label(s).
375
+ guidance_scale (`float`, *optional*):
376
+ CFG scale. Enabled when `guidance_scale > 1`.
377
+ noise_scale (`float`, *optional*, defaults to `1.0`):
378
+ Std of the initial noise. These checkpoints are trained at 256Γ—256 with unit-scale FLUX.2 latents.
379
+ num_inference_steps (`int`, *optional*, defaults to 50):
380
+ The number of denoising steps.
381
+ output_type (`str`, *optional*, defaults to `"pil"`):
382
+ `"pil"`, `"np"`, `"pt"`, or `"latent"`.
383
+ return_dict (`bool`, *optional*, defaults to `True`):
384
+ Whether to return an [`ImagePipelineOutput`].
385
+ """
386
+ if num_inference_steps < 2:
387
+ raise ValueError("num_inference_steps must be >= 2.")
388
+ if output_type not in {"pil", "np", "pt", "latent"}:
389
+ raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
390
+
391
+ if t_eps is not None:
392
+ self.t_eps = t_eps
393
+ if hasattr(self.scheduler, "register_to_config"):
394
+ self.scheduler.register_to_config(t_eps=t_eps)
395
+
396
+ class_label_ids = self._normalize_class_labels(class_labels)
397
+ if guidance_scale is None:
398
+ guidance_scale = 1.0
399
+ do_classifier_free_guidance = guidance_scale > 1.0
400
+
401
+ batch_size = len(class_label_ids)
402
+ latent_size = int(self.transformer.config.sample_size)
403
+ channels = int(self.transformer.config.in_channels)
404
+ null_class_val = int(
405
+ getattr(self.transformer.config, "num_classes", getattr(self.transformer.config, "num_class_embeds", 1000))
406
+ )
407
+ noise_scale = 1.0 if noise_scale is None else float(noise_scale)
408
+
409
+ latents = noise_scale * randn_tensor(
410
+ shape=(batch_size, channels, latent_size, latent_size),
411
+ generator=generator,
412
+ device=self._execution_device,
413
+ dtype=torch.float32,
414
+ )
415
+
416
+ class_labels_t = torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
417
+ class_labels_t = class_labels_t.clamp(0, null_class_val - 1)
418
+ class_null = torch.full_like(class_labels_t, null_class_val)
419
+
420
+ latents = self._run_sampler(
421
+ latents,
422
+ class_labels_t,
423
+ class_null,
424
+ num_inference_steps,
425
+ do_classifier_free_guidance,
426
+ guidance_scale,
427
+ guidance_interval_min,
428
+ guidance_interval_max,
429
+ )
430
+
431
+ if output_type == "latent":
432
+ if not return_dict:
433
+ return (latents,)
434
+ return ImagePipelineOutput(images=latents)
435
+
436
+ if self.vae is not None:
437
+ images_pt = decode_flux2_latents(self.vae, latents)
438
+ else:
439
+ images_pt = latents
440
+
441
+ if not torch.isfinite(images_pt).all():
442
+ raise RuntimeError(
443
+ "JLT generation produced non-finite values before image conversion. "
444
+ "Restart the notebook kernel and re-run the pipeline load cell."
445
+ )
446
+
447
+ if output_type in {"latent", "pt"}:
448
+ images = images_pt
449
+ else:
450
+ images = self.image_processor.postprocess(images_pt, output_type=output_type)
451
+
452
+ self.maybe_free_model_hooks()
453
+
454
+ if not return_dict:
455
+ return (images,)
456
+ return ImagePipelineOutput(images=images)
JLT-H-1/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "JLTScheduler",
3
+ "_diffusers_version": "0.39.0",
4
+ "num_train_timesteps": 1000,
5
+ "prediction_type": "sample",
6
+ "solver": "heun",
7
+ "t_eps": 0.05
8
+ }
JLT-H-1/scheduler/scheduling_jlt.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom scheduler: JLTScheduler.
2
+
3
+ JLT integrates a clean-latent ODE. Time runs from 0 (noise) to 1 (data):
4
+
5
+ z_t = t * x + (1 - t) * eps
6
+
7
+ The transformer predicts clean latent ``x`` by default (``prediction_type="sample"``).
8
+ ``step()`` integrates ``dz/dt``. Heun uses a predictor/corrector pair; the last
9
+ interval is always Euler because velocity is singular at ``t = 1``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
19
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
20
+ from diffusers.utils import BaseOutput
21
+
22
+
23
+ def velocity_from_prediction(
24
+ sample: torch.Tensor,
25
+ model_output: torch.Tensor,
26
+ timestep: Union[float, torch.Tensor],
27
+ *,
28
+ prediction_type: str = "sample",
29
+ t_eps: float = 5e-2,
30
+ ) -> torch.Tensor:
31
+ """Convert a JLT model output to ODE velocity ``dz/dt``.
32
+
33
+ Follows the official JiT pipeline (diffusers#13098): compute velocity in fp32
34
+ and clamp the ``1 / (1 - t)`` denominator at ``t_eps`` (default 0.05).
35
+ """
36
+ if prediction_type == "velocity":
37
+ return model_output.float()
38
+ if prediction_type != "sample":
39
+ raise ValueError("prediction_type must be one of: 'sample', 'velocity'.")
40
+
41
+ sample = sample.float()
42
+ model_output = model_output.float()
43
+ t = torch.as_tensor(timestep, device=sample.device, dtype=torch.float32)
44
+ while t.ndim < sample.ndim:
45
+ t = t.unsqueeze(-1)
46
+ denom = (1.0 - t).clamp(min=t_eps)
47
+ return (model_output - sample) / denom
48
+
49
+
50
+ @dataclass
51
+ class JLTSchedulerOutput(BaseOutput):
52
+ prev_sample: torch.Tensor
53
+
54
+
55
+ class JLTScheduler(SchedulerMixin, ConfigMixin):
56
+ """Clean-latent ODE scheduler for JLT (``t``: 0 -> 1)."""
57
+
58
+ config_name = "scheduler_config.json"
59
+ _compatibles = []
60
+ order = 2
61
+
62
+ @register_to_config
63
+ def __init__(
64
+ self,
65
+ num_train_timesteps: int = 1000,
66
+ solver: str = "heun",
67
+ prediction_type: str = "sample",
68
+ t_eps: float = 5e-2,
69
+ ):
70
+ if solver not in {"heun", "euler"}:
71
+ raise ValueError("solver must be one of: 'heun', 'euler'.")
72
+ if prediction_type not in {"sample", "velocity"}:
73
+ raise ValueError("prediction_type must be one of: 'sample', 'velocity'.")
74
+
75
+ self.timesteps: Optional[torch.Tensor] = None
76
+ self.schedule: Optional[torch.Tensor] = None
77
+ self.num_inference_steps: Optional[int] = None
78
+ self._step_plan: List[dict] = []
79
+ self._step_index: Optional[int] = None
80
+ self._begin_index: Optional[int] = None
81
+ self._heun_sample: Optional[torch.Tensor] = None
82
+ self._heun_velocity: Optional[torch.Tensor] = None
83
+ self._reset_heun_state()
84
+
85
+ @property
86
+ def init_noise_sigma(self) -> float:
87
+ return 1.0
88
+
89
+ @property
90
+ def step_index(self) -> Optional[int]:
91
+ return self._step_index
92
+
93
+ @property
94
+ def begin_index(self) -> Optional[int]:
95
+ return self._begin_index
96
+
97
+ def set_begin_index(self, begin_index: int = 0) -> None:
98
+ self._begin_index = begin_index
99
+
100
+ def set_timesteps(
101
+ self,
102
+ num_inference_steps: int,
103
+ device: Union[str, torch.device, None] = None,
104
+ ) -> None:
105
+ """Build the `t: 0 β†’ 1` knot schedule and Heun/Euler step plan."""
106
+ if num_inference_steps < 1:
107
+ raise ValueError("num_inference_steps must be >= 1.")
108
+ if self.config.solver == "heun" and num_inference_steps < 2:
109
+ raise ValueError("Heun solver requires num_inference_steps >= 2.")
110
+
111
+ knots = torch.linspace(0.0, 1.0, num_inference_steps + 1, device=device, dtype=torch.float32)
112
+ plan: List[dict] = []
113
+ if self.config.solver == "heun":
114
+ for idx in range(num_inference_steps - 1):
115
+ t_cur = float(knots[idx])
116
+ t_next = float(knots[idx + 1])
117
+ plan.append({"kind": "heun_predict", "t_model": t_cur, "t_cur": t_cur, "t_next": t_next})
118
+ plan.append({"kind": "heun_correct", "t_model": t_next, "t_cur": t_cur, "t_next": t_next})
119
+ plan.append(
120
+ {
121
+ "kind": "euler",
122
+ "t_model": float(knots[-2]),
123
+ "t_cur": float(knots[-2]),
124
+ "t_next": float(knots[-1]),
125
+ }
126
+ )
127
+ else:
128
+ for idx in range(num_inference_steps):
129
+ plan.append(
130
+ {
131
+ "kind": "euler",
132
+ "t_model": float(knots[idx]),
133
+ "t_cur": float(knots[idx]),
134
+ "t_next": float(knots[idx + 1]),
135
+ }
136
+ )
137
+
138
+ self.num_inference_steps = num_inference_steps
139
+ self.schedule = knots
140
+ self._step_plan = plan
141
+ self.timesteps = torch.tensor([item["t_model"] for item in plan], device=device, dtype=torch.float32)
142
+ self._step_index = 0 if self._begin_index is None else self._begin_index
143
+ self._reset_heun_state()
144
+
145
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
146
+ del timestep
147
+ return sample
148
+
149
+ def scale_noise(
150
+ self,
151
+ sample: torch.Tensor,
152
+ timestep: Union[float, torch.Tensor],
153
+ noise: torch.Tensor,
154
+ ) -> torch.Tensor:
155
+ """Forward process ``z = t * x + (1 - t) * eps``."""
156
+ t = torch.as_tensor(timestep, device=sample.device, dtype=sample.dtype)
157
+ while t.ndim < sample.ndim:
158
+ t = t.unsqueeze(-1)
159
+ return t * sample + (1.0 - t) * noise
160
+
161
+ def velocity_from_prediction(
162
+ self,
163
+ sample: torch.Tensor,
164
+ model_output: torch.Tensor,
165
+ timestep: Union[float, torch.Tensor],
166
+ *,
167
+ prediction_type: Optional[str] = None,
168
+ t_eps: Optional[float] = None,
169
+ ) -> torch.Tensor:
170
+ return velocity_from_prediction(
171
+ sample,
172
+ model_output,
173
+ timestep,
174
+ prediction_type=prediction_type or self.config.prediction_type,
175
+ t_eps=self.config.t_eps if t_eps is None else t_eps,
176
+ )
177
+
178
+ def _reset_heun_state(self) -> None:
179
+ self._heun_sample = None
180
+ self._heun_velocity = None
181
+
182
+ def _resolve_step_index(self, timestep: Union[float, torch.Tensor, None]) -> int:
183
+ if self.timesteps is None or not self._step_plan:
184
+ raise ValueError("Call `set_timesteps` before `step`.")
185
+ if self._step_index is not None:
186
+ return self._step_index
187
+ if timestep is None:
188
+ return 0
189
+
190
+ t_value = float(timestep) if not isinstance(timestep, torch.Tensor) else float(timestep.reshape(-1)[0])
191
+ matches = (self.timesteps - t_value).abs() < 1e-6
192
+ if matches.any():
193
+ return int(matches.nonzero(as_tuple=False)[0].item())
194
+ return 0
195
+
196
+ def _broadcast_dt(self, t_cur: float, t_next: float, sample: torch.Tensor) -> torch.Tensor:
197
+ dt = torch.as_tensor(t_next - t_cur, device=sample.device, dtype=sample.dtype)
198
+ while dt.ndim < sample.ndim:
199
+ dt = dt.unsqueeze(-1)
200
+ return dt
201
+
202
+ def step(
203
+ self,
204
+ model_output: torch.Tensor,
205
+ timestep: Union[float, torch.Tensor, None],
206
+ sample: torch.Tensor,
207
+ return_dict: bool = True,
208
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
209
+ prediction_type: Optional[str] = None,
210
+ t_eps: Optional[float] = None,
211
+ ) -> Union[JLTSchedulerOutput, Tuple[torch.Tensor]]:
212
+ """Advance one scheduled ODE step. `model_output` is clean-`x` or velocity."""
213
+ del generator
214
+ step_index = self._resolve_step_index(timestep)
215
+ if step_index >= len(self._step_plan):
216
+ raise ValueError("Scheduler has already reached the final timestep.")
217
+
218
+ plan = self._step_plan[step_index]
219
+ sample = sample.to(dtype=torch.float32)
220
+ velocity = self.velocity_from_prediction(
221
+ sample,
222
+ model_output.to(dtype=sample.dtype, device=sample.device),
223
+ plan["t_model"],
224
+ prediction_type=prediction_type,
225
+ t_eps=t_eps,
226
+ )
227
+ dt = self._broadcast_dt(plan["t_cur"], plan["t_next"], sample)
228
+
229
+ kind = plan["kind"]
230
+ if kind == "heun_predict":
231
+ self._heun_sample = sample
232
+ self._heun_velocity = velocity
233
+ prev_sample = sample + dt * velocity
234
+ elif kind == "heun_correct":
235
+ if self._heun_sample is None or self._heun_velocity is None:
236
+ raise RuntimeError("Heun corrector called before predictor. Call `set_timesteps` and step in order.")
237
+ prev_sample = self._heun_sample + dt * 0.5 * (self._heun_velocity + velocity)
238
+ self._reset_heun_state()
239
+ else:
240
+ prev_sample = sample + dt * velocity
241
+ self._reset_heun_state()
242
+
243
+ self._step_index = step_index + 1
244
+
245
+ if not return_dict:
246
+ return (prev_sample,)
247
+ return JLTSchedulerOutput(prev_sample=prev_sample)
248
+
249
+ def __len__(self) -> int:
250
+ return int(self.config.num_train_timesteps)
JLT-H-1/transformer/config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "JLTTransformer2DModel",
3
+ "_diffusers_version": "0.39.0",
4
+ "attention_dropout": 0.0,
5
+ "dropout": 0.2,
6
+ "hidden_size": 1280,
7
+ "in_channels": 128,
8
+ "loop_count": 0,
9
+ "loop_indices": null,
10
+ "mask_prob": 0.0,
11
+ "mask_ratio": 0.0,
12
+ "mlp_ratio": 4.0,
13
+ "model_type": "JiT-H/1",
14
+ "norm_eps": 1e-06,
15
+ "num_attention_heads": 20,
16
+ "num_class_embeds": null,
17
+ "num_classes": 1000,
18
+ "num_layers": 32,
19
+ "patch_size": 1,
20
+ "sample_size": 16
21
+ }
JLT-H-1/transformer/transformer_jlt.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JLT transformer: class-conditional clean-latent (or pixel) DiT.
2
+
3
+ Architecture hyperparameters are read from `config.json` / constructor kwargs.
4
+ Named training presets such as `JiT-B/1` are not part of this module.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from typing import List, Optional, Tuple
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
16
+ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin
17
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
18
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
19
+ from diffusers.models.modeling_utils import ModelMixin
20
+ from diffusers.models.normalization import RMSNorm
21
+
22
+
23
+ def rotate_half(x):
24
+ x = x.view(*x.shape[:-1], x.shape[-1] // 2, 2)
25
+ x1, x2 = x.unbind(dim=-1)
26
+ x = torch.stack((-x2, x1), dim=-1)
27
+ return x.view(*x.shape[:-2], -1)
28
+
29
+
30
+ class JLTRotaryEmbedding(nn.Module):
31
+ """2D axial RoPE for JLT attention, matching the official JiT implementation."""
32
+
33
+ def __init__(self, dim, pt_seq_len=16, ft_seq_len=None, theta=10000):
34
+ super().__init__()
35
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
36
+ if ft_seq_len is None:
37
+ ft_seq_len = pt_seq_len
38
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
39
+
40
+ freqs = torch.einsum("..., f -> ... f", t, freqs)
41
+ freqs = freqs.repeat_interleave(2, dim=-1)
42
+ freqs_h = freqs[:, None, :].expand(-1, freqs.shape[0], -1)
43
+ freqs_w = freqs[None, :, :].expand(freqs.shape[0], -1, -1)
44
+ freqs = torch.cat((freqs_h, freqs_w), dim=-1)
45
+
46
+ self.register_buffer("freqs_cos", freqs.cos().view(-1, freqs.shape[-1]), persistent=False)
47
+ self.register_buffer("freqs_sin", freqs.sin().view(-1, freqs.shape[-1]), persistent=False)
48
+
49
+ def forward(self, tensor):
50
+ seq_len = tensor.shape[1]
51
+ freqs_cos = self.freqs_cos[:seq_len].to(dtype=tensor.dtype)
52
+ freqs_sin = self.freqs_sin[:seq_len].to(dtype=tensor.dtype)
53
+ return tensor * freqs_cos[:, None, :] + rotate_half(tensor) * freqs_sin[:, None, :]
54
+
55
+
56
+ def modulate(x, shift, scale):
57
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
58
+
59
+
60
+ class JLTPatchEmbed(nn.Module):
61
+ """Conv patch embedder for latents (`patch_size=1`) or pixels."""
62
+
63
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, bias=True):
64
+ super().__init__()
65
+ img_size = (img_size, img_size)
66
+ patch_size = (patch_size, patch_size)
67
+ self.img_size = img_size
68
+ self.patch_size = patch_size
69
+ self.num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
70
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
71
+
72
+ def forward(self, x):
73
+ return self.proj(x).flatten(2).transpose(1, 2)
74
+
75
+
76
+ class JLTTimestepEmbedder(nn.Module):
77
+ """Sinusoidal timestep MLP used for adaLN conditioning."""
78
+
79
+ def __init__(self, hidden_size, frequency_embedding_size=256):
80
+ super().__init__()
81
+ self.mlp = nn.Sequential(
82
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
83
+ nn.SiLU(),
84
+ nn.Linear(hidden_size, hidden_size, bias=True),
85
+ )
86
+ self.frequency_embedding_size = frequency_embedding_size
87
+
88
+ @staticmethod
89
+ def timestep_embedding(t, dim, max_period=10000):
90
+ half = dim // 2
91
+ freqs = torch.exp(
92
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half
93
+ )
94
+ args = t.float().unsqueeze(-1) * freqs
95
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
96
+ if dim % 2:
97
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[..., :1])], dim=-1)
98
+ return embedding.to(t.dtype)
99
+
100
+ def forward(self, t, dtype=None):
101
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
102
+ if dtype is not None:
103
+ t_freq = t_freq.to(dtype=dtype)
104
+ return self.mlp(t_freq)
105
+
106
+
107
+ class JLTLabelEmbedder(nn.Module):
108
+ """Class embedding table with one extra null class for CFG."""
109
+
110
+ def __init__(self, num_classes, hidden_size):
111
+ super().__init__()
112
+ self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
113
+ self.num_classes = num_classes
114
+
115
+ def forward(self, labels):
116
+ return self.embedding_table(labels)
117
+
118
+
119
+ class JLTAttnProcessor:
120
+ """Official JiT-style attention: split `to_q` / `to_k` / `to_v` + `dispatch_attention_fn`."""
121
+
122
+ _attention_backend = None
123
+ _parallel_config = None
124
+
125
+ def __call__(self, attn: "JLTAttention", hidden_states: torch.Tensor, rope=None) -> torch.Tensor:
126
+ query = attn.to_q(hidden_states).unflatten(2, (attn.num_heads, attn.head_dim))
127
+ key = attn.to_k(hidden_states).unflatten(2, (attn.num_heads, attn.head_dim))
128
+ value = attn.to_v(hidden_states).unflatten(2, (attn.num_heads, attn.head_dim))
129
+
130
+ query = attn.norm_q(query)
131
+ key = attn.norm_k(key)
132
+
133
+ if rope is not None:
134
+ query = rope(query)
135
+ key = rope(key)
136
+
137
+ hidden_states = dispatch_attention_fn(
138
+ query,
139
+ key,
140
+ value,
141
+ dropout_p=attn.attn_drop if attn.training else 0.0,
142
+ is_causal=False,
143
+ backend=self._attention_backend,
144
+ parallel_config=self._parallel_config,
145
+ )
146
+ hidden_states = hidden_states.flatten(2, 3)
147
+ hidden_states = attn.to_out[0](hidden_states)
148
+ hidden_states = attn.to_out[1](hidden_states)
149
+ return hidden_states
150
+
151
+
152
+ class JLTAttention(nn.Module, AttentionModuleMixin):
153
+ """Multi-head self-attention with QK RMSNorm, RoPE, and separate QKV projections."""
154
+
155
+ _default_processor_cls = JLTAttnProcessor
156
+ _available_processors = [JLTAttnProcessor]
157
+
158
+ def __init__(
159
+ self, dim, num_heads=8, qkv_bias=True, qk_norm=True, attn_drop=0.0, proj_drop=0.0, eps=1e-6, processor=None
160
+ ):
161
+ super().__init__()
162
+ self.num_heads = num_heads
163
+ self.heads = num_heads
164
+ self.head_dim = dim // num_heads
165
+ self.attn_drop = attn_drop
166
+
167
+ self.norm_q = RMSNorm(self.head_dim, eps=eps) if qk_norm else nn.Identity()
168
+ self.norm_k = RMSNorm(self.head_dim, eps=eps) if qk_norm else nn.Identity()
169
+
170
+ self.to_q = nn.Linear(dim, dim, bias=qkv_bias)
171
+ self.to_k = nn.Linear(dim, dim, bias=qkv_bias)
172
+ self.to_v = nn.Linear(dim, dim, bias=qkv_bias)
173
+ self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(proj_drop)])
174
+
175
+ if processor is None:
176
+ processor = self._default_processor_cls()
177
+ self.set_processor(processor)
178
+
179
+ def forward(self, x, rope=None):
180
+ return self.processor(self, x, rope=rope)
181
+
182
+
183
+ class JLTSwiGLUFFN(nn.Module):
184
+ """SwiGLU feed-forward block (`w12` fused, then `w3`)."""
185
+
186
+ def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
187
+ super().__init__()
188
+ hidden_dim = int(hidden_dim * 2 / 3)
189
+ self.w12 = nn.Linear(dim, 2 * hidden_dim, bias=bias)
190
+ self.w3 = nn.Linear(hidden_dim, dim, bias=bias)
191
+ self.ffn_dropout = nn.Dropout(drop)
192
+
193
+ def forward(self, x):
194
+ x12 = self.w12(x)
195
+ x1, x2 = x12.chunk(2, dim=-1)
196
+ return self.w3(self.ffn_dropout(F.silu(x1) * x2))
197
+
198
+
199
+ class JLTBlock(nn.Module):
200
+ """Pre-norm transformer block with adaLN-Zero modulation."""
201
+
202
+ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0, eps=1e-6):
203
+ super().__init__()
204
+ self.norm1 = RMSNorm(hidden_size, eps=eps)
205
+ self.attn = JLTAttention(
206
+ hidden_size,
207
+ num_heads=num_heads,
208
+ qkv_bias=True,
209
+ qk_norm=True,
210
+ attn_drop=attn_drop,
211
+ proj_drop=proj_drop,
212
+ eps=eps,
213
+ )
214
+ self.norm2 = RMSNorm(hidden_size, eps=eps)
215
+ self.mlp = JLTSwiGLUFFN(hidden_size, int(hidden_size * mlp_ratio), drop=proj_drop)
216
+ self.act = nn.SiLU()
217
+ self.adaLN_modulation = nn.Linear(hidden_size, 6 * hidden_size, bias=True)
218
+
219
+ def forward(self, x, c, feat_rope=None):
220
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(self.act(c)).chunk(6, dim=-1)
221
+ x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
222
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
223
+ return x
224
+
225
+
226
+ class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
227
+ r"""
228
+ 2D transformer for class-conditional clean-latent generation ([JLT](https://arxiv.org/abs/2605.27102)).
229
+
230
+ The model predicts the clean sample `x`. Sampling uses [`JLTScheduler`] (`t`: 0 noise β†’ 1 data). Latent
231
+ checkpoints use FLUX.2 latents (`in_channels=128`, `sample_size` is the latent grid).
232
+
233
+ Args:
234
+ sample_size (`int`, defaults to 16): Spatial size of the input grid.
235
+ patch_size (`int`, defaults to 1): Patch embed kernel / stride.
236
+ in_channels (`int`, defaults to 128): Input/output channels.
237
+ hidden_size (`int`, defaults to 768): Transformer width.
238
+ num_layers (`int`, defaults to 12): Number of `JLTBlock`s.
239
+ num_attention_heads (`int`, defaults to 12): Attention heads.
240
+ mlp_ratio (`float`, defaults to 4.0): SwiGLU expansion.
241
+ num_classes (`int`, defaults to 1000): ImageNet classes (plus a null CFG class).
242
+ model_type (`str`, *optional*): Training-name label stored in `config.json` only.
243
+ """
244
+
245
+ _supports_gradient_checkpointing = True
246
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
247
+ _no_split_modules = ["JLTBlock"]
248
+ _repeated_blocks = ["JLTBlock"]
249
+
250
+ @register_to_config
251
+ def __init__(
252
+ self,
253
+ sample_size: int = 16,
254
+ patch_size: int = 1,
255
+ in_channels: int = 128,
256
+ hidden_size: int = 768,
257
+ num_layers: int = 12,
258
+ num_attention_heads: int = 12,
259
+ mlp_ratio: float = 4.0,
260
+ attention_dropout: float = 0.0,
261
+ dropout: float = 0.0,
262
+ num_classes: int = 1000,
263
+ norm_eps: float = 1e-6,
264
+ model_type: str | None = None,
265
+ num_class_embeds: int | None = None,
266
+ mask_prob: float = 0.0,
267
+ mask_ratio: float = 0.0,
268
+ loop_indices: Optional[List[int]] = None,
269
+ loop_count: int = 0,
270
+ ):
271
+ super().__init__()
272
+ if num_class_embeds is not None:
273
+ num_classes = int(num_class_embeds)
274
+
275
+ self.sample_size = sample_size
276
+ self.patch_size = patch_size
277
+ self.in_channels = in_channels
278
+ self.out_channels = in_channels
279
+ self.hidden_size = hidden_size
280
+ self.num_layers = num_layers
281
+ self.num_attention_heads = num_attention_heads
282
+ self.mask_prob = float(mask_prob)
283
+ self.mask_ratio = float(mask_ratio)
284
+ self.loop_count = int(loop_count)
285
+ self.gradient_checkpointing = False
286
+
287
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, hidden_size))
288
+ nn.init.normal_(self.mask_token, std=0.02)
289
+
290
+ self.loop_indices: Optional[Tuple[int, ...]] = None
291
+ if loop_indices and self.loop_count > 0:
292
+ sorted_idx = sorted(int(x) for x in loop_indices)
293
+ if len(set(sorted_idx)) != len(sorted_idx):
294
+ raise ValueError(f"loop_indices must be unique, got {loop_indices}.")
295
+ for i in range(1, len(sorted_idx)):
296
+ if sorted_idx[i] != sorted_idx[i - 1] + 1:
297
+ raise ValueError(f"loop_indices must be consecutive integers, got {sorted_idx}.")
298
+ if sorted_idx[0] < 0 or sorted_idx[-1] >= num_layers:
299
+ raise ValueError(f"loop_indices must lie in [0, {num_layers}), got {sorted_idx}.")
300
+ self.loop_indices = tuple(sorted_idx)
301
+
302
+ self.t_embedder = JLTTimestepEmbedder(hidden_size)
303
+ self.y_embedder = JLTLabelEmbedder(num_classes, hidden_size)
304
+ self.x_embedder = JLTPatchEmbed(sample_size, patch_size, in_channels, hidden_size, bias=True)
305
+
306
+ half_head_dim = hidden_size // num_attention_heads // 2
307
+ hw_seq_len = sample_size // patch_size
308
+ self.feat_rope = JLTRotaryEmbedding(dim=half_head_dim, pt_seq_len=hw_seq_len)
309
+
310
+ self.blocks = nn.ModuleList(
311
+ [
312
+ JLTBlock(
313
+ hidden_size,
314
+ num_attention_heads,
315
+ mlp_ratio=mlp_ratio,
316
+ attn_drop=attention_dropout if (num_layers // 4 * 3 > i >= num_layers // 4) else 0.0,
317
+ proj_drop=dropout if (num_layers // 4 * 3 > i >= num_layers // 4) else 0.0,
318
+ eps=norm_eps,
319
+ )
320
+ for i in range(num_layers)
321
+ ]
322
+ )
323
+
324
+ self.norm_final = RMSNorm(hidden_size, eps=norm_eps)
325
+ self.linear_final = nn.Linear(hidden_size, patch_size * patch_size * self.out_channels, bias=True)
326
+ self.act_final = nn.SiLU()
327
+ self.adaLN_modulation_final = nn.Linear(hidden_size, 2 * hidden_size, bias=True)
328
+
329
+ self.initialize_weights()
330
+
331
+ def initialize_weights(self):
332
+ def _basic_init(module):
333
+ if isinstance(module, nn.Linear):
334
+ torch.nn.init.xavier_uniform_(module.weight)
335
+ if module.bias is not None:
336
+ nn.init.constant_(module.bias, 0)
337
+
338
+ self.apply(_basic_init)
339
+
340
+ w = self.x_embedder.proj.weight.data
341
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
342
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
343
+ nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
344
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
345
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
346
+
347
+ for block in self.blocks:
348
+ nn.init.constant_(block.adaLN_modulation.weight, 0)
349
+ nn.init.constant_(block.adaLN_modulation.bias, 0)
350
+
351
+ nn.init.constant_(self.adaLN_modulation_final.weight, 0)
352
+ nn.init.constant_(self.adaLN_modulation_final.bias, 0)
353
+ nn.init.constant_(self.linear_final.weight, 0)
354
+ nn.init.constant_(self.linear_final.bias, 0)
355
+
356
+ def _block_schedule(self) -> List[int]:
357
+ if self.loop_indices is not None and self.loop_count > 0:
358
+ a, b = self.loop_indices[0], self.loop_indices[-1]
359
+ return list(range(0, a)) + list(range(a, b + 1)) * self.loop_count + list(range(b + 1, len(self.blocks)))
360
+ return list(range(len(self.blocks)))
361
+
362
+ def forward(
363
+ self,
364
+ sample: torch.Tensor,
365
+ timestep: torch.Tensor,
366
+ class_labels: torch.Tensor,
367
+ return_dict: bool = True,
368
+ return_features: bool = False,
369
+ feature_layers: Optional[List[int]] = None,
370
+ ):
371
+ """Predict the clean sample from a noisy latent / image `sample` at JLT time `timestep`."""
372
+ t = torch.as_tensor(timestep, device=sample.device)
373
+ if t.ndim == 0:
374
+ t = t.repeat(sample.shape[0])
375
+ elif t.ndim == 1 and t.shape[0] == 1 and sample.shape[0] > 1:
376
+ t = t.repeat(sample.shape[0])
377
+
378
+ t_emb = self.t_embedder(t, dtype=sample.dtype)
379
+ y_emb = self.y_embedder(class_labels).to(dtype=sample.dtype)
380
+ if t_emb.ndim == 3:
381
+ y_emb = y_emb.unsqueeze(1)
382
+ c = t_emb + y_emb
383
+
384
+ x = self.x_embedder(sample)
385
+ if self.training and self.mask_prob > 0.0 and self.mask_ratio > 0.0:
386
+ batch, num_tokens, _ = x.shape
387
+ s_mask = torch.rand(batch, device=x.device) < self.mask_prob
388
+ t_mask = torch.rand(batch, num_tokens, device=x.device) < self.mask_ratio
389
+ mask = (s_mask.unsqueeze(1) & t_mask).unsqueeze(-1)
390
+ x = torch.where(mask, self.mask_token.to(x.dtype), x)
391
+
392
+ target_layers = set(feature_layers or [])
393
+ features = {} if return_features else None
394
+
395
+ for layer_idx in self._block_schedule():
396
+ if self.training and self.gradient_checkpointing:
397
+ x = torch.utils.checkpoint.checkpoint(
398
+ self.blocks[layer_idx], x, c, self.feat_rope, use_reentrant=False
399
+ )
400
+ else:
401
+ x = self.blocks[layer_idx](x, c, self.feat_rope)
402
+ if return_features and layer_idx in target_layers:
403
+ features[layer_idx] = x
404
+
405
+ shift, scale = self.adaLN_modulation_final(self.act_final(c)).chunk(2, dim=-1)
406
+ x = modulate(self.norm_final(x), shift, scale)
407
+ x = self.linear_final(x)
408
+
409
+ height = width = int(x.shape[1] ** 0.5)
410
+ x = x.reshape(x.shape[0], height, width, self.patch_size, self.patch_size, self.out_channels)
411
+ x = torch.einsum("nhwpqc->nchpwq", x)
412
+ output = x.reshape(x.shape[0], self.out_channels, height * self.patch_size, width * self.patch_size)
413
+
414
+ if return_features:
415
+ if not return_dict:
416
+ return (output, features)
417
+ return Transformer2DModelOutput(sample=output), features
418
+
419
+ if not return_dict:
420
+ return (output,)
421
+ return Transformer2DModelOutput(sample=output)
JLT-H-1/vae/config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKLFlux2",
3
+ "_diffusers_version": "0.37.0.dev0",
4
+ "_name_or_path": "black-forest-labs/FLUX.2-dev",
5
+ "act_fn": "silu",
6
+ "batch_norm_eps": 0.0001,
7
+ "batch_norm_momentum": 0.1,
8
+ "block_out_channels": [
9
+ 128,
10
+ 256,
11
+ 512,
12
+ 512
13
+ ],
14
+ "down_block_types": [
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D",
17
+ "DownEncoderBlock2D",
18
+ "DownEncoderBlock2D"
19
+ ],
20
+ "force_upcast": true,
21
+ "in_channels": 3,
22
+ "latent_channels": 32,
23
+ "layers_per_block": 2,
24
+ "mid_block_add_attention": true,
25
+ "norm_num_groups": 32,
26
+ "out_channels": 3,
27
+ "patch_size": [
28
+ 2,
29
+ 2
30
+ ],
31
+ "sample_size": 1024,
32
+ "up_block_types": [
33
+ "UpDecoderBlock2D",
34
+ "UpDecoderBlock2D",
35
+ "UpDecoderBlock2D",
36
+ "UpDecoderBlock2D"
37
+ ],
38
+ "use_post_quant_conv": true,
39
+ "use_quant_conv": true
40
+ }
JLT-L-1/pipeline.py CHANGED
@@ -69,9 +69,11 @@ def _solver_from_scheduler(scheduler) -> str:
69
 
70
  class JLTPipeline(DiffusionPipeline):
71
  r"""
72
- Pipeline for class-conditional image generation with JLT (Clean-Latent JiT).
73
 
74
- Latent models (`in_channels=128`) require a FLUX.2 VAE attached for `output_type="pil"`.
 
 
75
  """
76
 
77
  model_cpu_offload_seq = "transformer->vae"
@@ -372,9 +374,8 @@ class JLTPipeline(DiffusionPipeline):
372
  ImageNet class id(s) or English label(s).
373
  guidance_scale (`float`, *optional*):
374
  CFG scale. Enabled when `guidance_scale > 1`.
375
- noise_scale (`float`, *optional*, defaults to `None`):
376
- Std of the initial noise. JiT/JLT scale this with resolution to keep SNR constant
377
- (`1.0` at 256, `2.0` at 512, `4.0` at 1024). See huggingface/diffusers#13098.
378
  num_inference_steps (`int`, *optional*, defaults to 50):
379
  The number of denoising steps.
380
  output_type (`str`, *optional*, defaults to `"pil"`):
@@ -400,13 +401,10 @@ class JLTPipeline(DiffusionPipeline):
400
  batch_size = len(class_label_ids)
401
  latent_size = int(self.transformer.config.sample_size)
402
  channels = int(self.transformer.config.in_channels)
403
- # Official JiT uses pixel `sample_size`. JLT latent models store the latent grid.
404
- image_size = latent_size * 16 if channels == 128 else latent_size
405
  null_class_val = int(
406
  getattr(self.transformer.config, "num_classes", getattr(self.transformer.config, "num_class_embeds", 1000))
407
  )
408
-
409
- noise_scale = noise_scale if noise_scale is not None else (image_size / 256.0)
410
 
411
  latents = noise_scale * randn_tensor(
412
  shape=(batch_size, channels, latent_size, latent_size),
 
69
 
70
  class JLTPipeline(DiffusionPipeline):
71
  r"""
72
+ Class-conditional JLT sampler.
73
 
74
+ Starts from unit Gaussian noise in FLUX.2 latent space (`noise_scale=1.0`) at the
75
+ trained 256Γ—256 resolution, integrates `JLTScheduler` (Heun, last step Euler),
76
+ applies interval CFG in velocity space, and decodes FLUX.2 latents when a VAE is attached.
77
  """
78
 
79
  model_cpu_offload_seq = "transformer->vae"
 
374
  ImageNet class id(s) or English label(s).
375
  guidance_scale (`float`, *optional*):
376
  CFG scale. Enabled when `guidance_scale > 1`.
377
+ noise_scale (`float`, *optional*, defaults to `1.0`):
378
+ Std of the initial noise. These checkpoints are trained at 256Γ—256 with unit-scale FLUX.2 latents.
 
379
  num_inference_steps (`int`, *optional*, defaults to 50):
380
  The number of denoising steps.
381
  output_type (`str`, *optional*, defaults to `"pil"`):
 
401
  batch_size = len(class_label_ids)
402
  latent_size = int(self.transformer.config.sample_size)
403
  channels = int(self.transformer.config.in_channels)
 
 
404
  null_class_val = int(
405
  getattr(self.transformer.config, "num_classes", getattr(self.transformer.config, "num_class_embeds", 1000))
406
  )
407
+ noise_scale = 1.0 if noise_scale is None else float(noise_scale)
 
408
 
409
  latents = noise_scale * randn_tensor(
410
  shape=(batch_size, channels, latent_size, latent_size),
JLT-L-1/scheduler/scheduling_jlt.py CHANGED
@@ -102,6 +102,7 @@ class JLTScheduler(SchedulerMixin, ConfigMixin):
102
  num_inference_steps: int,
103
  device: Union[str, torch.device, None] = None,
104
  ) -> None:
 
105
  if num_inference_steps < 1:
106
  raise ValueError("num_inference_steps must be >= 1.")
107
  if self.config.solver == "heun" and num_inference_steps < 2:
@@ -208,6 +209,7 @@ class JLTScheduler(SchedulerMixin, ConfigMixin):
208
  prediction_type: Optional[str] = None,
209
  t_eps: Optional[float] = None,
210
  ) -> Union[JLTSchedulerOutput, Tuple[torch.Tensor]]:
 
211
  del generator
212
  step_index = self._resolve_step_index(timestep)
213
  if step_index >= len(self._step_plan):
 
102
  num_inference_steps: int,
103
  device: Union[str, torch.device, None] = None,
104
  ) -> None:
105
+ """Build the `t: 0 β†’ 1` knot schedule and Heun/Euler step plan."""
106
  if num_inference_steps < 1:
107
  raise ValueError("num_inference_steps must be >= 1.")
108
  if self.config.solver == "heun" and num_inference_steps < 2:
 
209
  prediction_type: Optional[str] = None,
210
  t_eps: Optional[float] = None,
211
  ) -> Union[JLTSchedulerOutput, Tuple[torch.Tensor]]:
212
+ """Advance one scheduled ODE step. `model_output` is clean-`x` or velocity."""
213
  del generator
214
  step_index = self._resolve_step_index(timestep)
215
  if step_index >= len(self._step_plan):
JLT-L-1/transformer/transformer_jlt.py CHANGED
@@ -1,4 +1,8 @@
1
- """JLT (Clean-Latent) Transformer for diffusers."""
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
@@ -24,6 +28,8 @@ def rotate_half(x):
24
 
25
 
26
  class JLTRotaryEmbedding(nn.Module):
 
 
27
  def __init__(self, dim, pt_seq_len=16, ft_seq_len=None, theta=10000):
28
  super().__init__()
29
  freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
@@ -52,6 +58,8 @@ def modulate(x, shift, scale):
52
 
53
 
54
  class JLTPatchEmbed(nn.Module):
 
 
55
  def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, bias=True):
56
  super().__init__()
57
  img_size = (img_size, img_size)
@@ -62,15 +70,12 @@ class JLTPatchEmbed(nn.Module):
62
  self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
63
 
64
  def forward(self, x):
65
- batch, _, height, width = x.shape
66
- if height != self.img_size[0] or width != self.img_size[1]:
67
- raise ValueError(
68
- f"Input image size ({height}*{width}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
69
- )
70
  return self.proj(x).flatten(2).transpose(1, 2)
71
 
72
 
73
  class JLTTimestepEmbedder(nn.Module):
 
 
74
  def __init__(self, hidden_size, frequency_embedding_size=256):
75
  super().__init__()
76
  self.mlp = nn.Sequential(
@@ -100,6 +105,8 @@ class JLTTimestepEmbedder(nn.Module):
100
 
101
 
102
  class JLTLabelEmbedder(nn.Module):
 
 
103
  def __init__(self, num_classes, hidden_size):
104
  super().__init__()
105
  self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
@@ -110,6 +117,8 @@ class JLTLabelEmbedder(nn.Module):
110
 
111
 
112
  class JLTAttnProcessor:
 
 
113
  _attention_backend = None
114
  _parallel_config = None
115
 
@@ -141,6 +150,8 @@ class JLTAttnProcessor:
141
 
142
 
143
  class JLTAttention(nn.Module, AttentionModuleMixin):
 
 
144
  _default_processor_cls = JLTAttnProcessor
145
  _available_processors = [JLTAttnProcessor]
146
 
@@ -170,6 +181,8 @@ class JLTAttention(nn.Module, AttentionModuleMixin):
170
 
171
 
172
  class JLTSwiGLUFFN(nn.Module):
 
 
173
  def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
174
  super().__init__()
175
  hidden_dim = int(hidden_dim * 2 / 3)
@@ -184,6 +197,8 @@ class JLTSwiGLUFFN(nn.Module):
184
 
185
 
186
  class JLTBlock(nn.Module):
 
 
187
  def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0, eps=1e-6):
188
  super().__init__()
189
  self.norm1 = RMSNorm(hidden_size, eps=eps)
@@ -209,6 +224,24 @@ class JLTBlock(nn.Module):
209
 
210
 
211
  class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  _supports_gradient_checkpointing = True
213
  _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
214
  _no_split_modules = ["JLTBlock"]
@@ -335,6 +368,7 @@ class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
335
  return_features: bool = False,
336
  feature_layers: Optional[List[int]] = None,
337
  ):
 
338
  t = torch.as_tensor(timestep, device=sample.device)
339
  if t.ndim == 0:
340
  t = t.repeat(sample.shape[0])
 
1
+ """JLT transformer: class-conditional clean-latent (or pixel) DiT.
2
+
3
+ Architecture hyperparameters are read from `config.json` / constructor kwargs.
4
+ Named training presets such as `JiT-B/1` are not part of this module.
5
+ """
6
 
7
  from __future__ import annotations
8
 
 
28
 
29
 
30
  class JLTRotaryEmbedding(nn.Module):
31
+ """2D axial RoPE for JLT attention, matching the official JiT implementation."""
32
+
33
  def __init__(self, dim, pt_seq_len=16, ft_seq_len=None, theta=10000):
34
  super().__init__()
35
  freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
 
58
 
59
 
60
  class JLTPatchEmbed(nn.Module):
61
+ """Conv patch embedder for latents (`patch_size=1`) or pixels."""
62
+
63
  def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, bias=True):
64
  super().__init__()
65
  img_size = (img_size, img_size)
 
70
  self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
71
 
72
  def forward(self, x):
 
 
 
 
 
73
  return self.proj(x).flatten(2).transpose(1, 2)
74
 
75
 
76
  class JLTTimestepEmbedder(nn.Module):
77
+ """Sinusoidal timestep MLP used for adaLN conditioning."""
78
+
79
  def __init__(self, hidden_size, frequency_embedding_size=256):
80
  super().__init__()
81
  self.mlp = nn.Sequential(
 
105
 
106
 
107
  class JLTLabelEmbedder(nn.Module):
108
+ """Class embedding table with one extra null class for CFG."""
109
+
110
  def __init__(self, num_classes, hidden_size):
111
  super().__init__()
112
  self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
 
117
 
118
 
119
  class JLTAttnProcessor:
120
+ """Official JiT-style attention: split `to_q` / `to_k` / `to_v` + `dispatch_attention_fn`."""
121
+
122
  _attention_backend = None
123
  _parallel_config = None
124
 
 
150
 
151
 
152
  class JLTAttention(nn.Module, AttentionModuleMixin):
153
+ """Multi-head self-attention with QK RMSNorm, RoPE, and separate QKV projections."""
154
+
155
  _default_processor_cls = JLTAttnProcessor
156
  _available_processors = [JLTAttnProcessor]
157
 
 
181
 
182
 
183
  class JLTSwiGLUFFN(nn.Module):
184
+ """SwiGLU feed-forward block (`w12` fused, then `w3`)."""
185
+
186
  def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
187
  super().__init__()
188
  hidden_dim = int(hidden_dim * 2 / 3)
 
197
 
198
 
199
  class JLTBlock(nn.Module):
200
+ """Pre-norm transformer block with adaLN-Zero modulation."""
201
+
202
  def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0, eps=1e-6):
203
  super().__init__()
204
  self.norm1 = RMSNorm(hidden_size, eps=eps)
 
224
 
225
 
226
  class JLTTransformer2DModel(ModelMixin, ConfigMixin, AttentionMixin):
227
+ r"""
228
+ 2D transformer for class-conditional clean-latent generation ([JLT](https://arxiv.org/abs/2605.27102)).
229
+
230
+ The model predicts the clean sample `x`. Sampling uses [`JLTScheduler`] (`t`: 0 noise β†’ 1 data). Latent
231
+ checkpoints use FLUX.2 latents (`in_channels=128`, `sample_size` is the latent grid).
232
+
233
+ Args:
234
+ sample_size (`int`, defaults to 16): Spatial size of the input grid.
235
+ patch_size (`int`, defaults to 1): Patch embed kernel / stride.
236
+ in_channels (`int`, defaults to 128): Input/output channels.
237
+ hidden_size (`int`, defaults to 768): Transformer width.
238
+ num_layers (`int`, defaults to 12): Number of `JLTBlock`s.
239
+ num_attention_heads (`int`, defaults to 12): Attention heads.
240
+ mlp_ratio (`float`, defaults to 4.0): SwiGLU expansion.
241
+ num_classes (`int`, defaults to 1000): ImageNet classes (plus a null CFG class).
242
+ model_type (`str`, *optional*): Training-name label stored in `config.json` only.
243
+ """
244
+
245
  _supports_gradient_checkpointing = True
246
  _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
247
  _no_split_modules = ["JLTBlock"]
 
368
  return_features: bool = False,
369
  feature_layers: Optional[List[int]] = None,
370
  ):
371
+ """Predict the clean sample from a noisy latent / image `sample` at JLT time `timestep`."""
372
  t = torch.as_tensor(timestep, device=sample.device)
373
  if t.ndim == 0:
374
  t = t.repeat(sample.shape[0])
README.md CHANGED
@@ -19,7 +19,7 @@ language:
19
 
20
  # JLT-diffusers
21
 
22
- Native [diffusers](https://github.com/huggingface/diffusers) checkpoints for **JLT** (Clean-Latent Prediction in Latent Diffusion Transformers). Each variant folder is self-contained:
23
 
24
  - `pipeline.py` β€” `JLTPipeline`
25
  - `scheduler/scheduling_jlt.py` β€” `JLTScheduler` (JLT time `t: 0 β†’ 1`, Heun / Euler)
@@ -32,7 +32,7 @@ Load with PyPI `diffusers` and `trust_remote_code=True`. No extra JLT package is
32
 
33
  ![JLT-B-1 demo](demo.png)
34
 
35
- Class: *golden retriever* (ImageNet 207) β€” JLT-B/1 at 256Γ—256, 50 Heun steps, `guidance_scale=2.9`, default `noise_scale=image_size/256` (`1.0` at 256), `torch_dtype=bfloat16`, seed 42.
36
 
37
  ## Available checkpoints
38
 
@@ -40,6 +40,7 @@ Class: *golden retriever* (ImageNet 207) β€” JLT-B/1 at 256Γ—256, 50 Heun steps,
40
  | --- | --- | --- | --- | ---: |
41
  | JLT-B/1 | [`JLT-B-1/`](JLT-B-1/) | 256Γ—256 | FLUX.2, patch /1 | 2.9 |
42
  | JLT-L/1 | [`JLT-L-1/`](JLT-L-1/) | 256Γ—256 | FLUX.2, patch /1 | 2.9 |
 
43
 
44
  ## ImageNet class labels
45
 
@@ -53,17 +54,14 @@ Each variant keeps an English `id2label` map in `model_index.json`.
53
  ## Inference
54
 
55
  ```python
56
- import importlib.util
57
- from pathlib import Path
58
  import torch
 
59
 
60
- model_dir = Path("./JLT-B-1")
61
- spec = importlib.util.spec_from_file_location("jlt_pipeline", model_dir / "pipeline.py")
62
- mod = importlib.util.module_from_spec(spec)
63
- spec.loader.exec_module(mod)
64
-
65
- pipe = mod.JLTPipeline.from_pretrained(
66
- str(model_dir),
67
  torch_dtype=torch.bfloat16,
68
  ).to("cuda")
69
 
@@ -77,18 +75,13 @@ image = pipe(
77
  image.save("demo.png")
78
  ```
79
 
80
- Or with native diffusers:
81
-
82
- ```python
83
- from pathlib import Path
84
- from diffusers import DiffusionPipeline
85
- import torch
86
 
87
- model_dir = Path("./JLT-B-1")
88
- pipe = DiffusionPipeline.from_pretrained(
89
- str(model_dir),
90
- custom_pipeline=str(model_dir / "pipeline.py"),
91
- trust_remote_code=True,
92
- torch_dtype=torch.bfloat16,
93
- ).to("cuda")
94
  ```
 
19
 
20
  # JLT-diffusers
21
 
22
+ Native [diffusers](https://github.com/huggingface/diffusers) checkpoints for **JLT** (Clean-Latent Prediction in Latent Diffusion Transformers). Paper: [arXiv:2605.27102](https://arxiv.org/abs/2605.27102). Code: [akatsuki-neo/JLT](https://github.com/akatsuki-neo/JLT). Each variant folder is self-contained:
23
 
24
  - `pipeline.py` β€” `JLTPipeline`
25
  - `scheduler/scheduling_jlt.py` β€” `JLTScheduler` (JLT time `t: 0 β†’ 1`, Heun / Euler)
 
32
 
33
  ![JLT-B-1 demo](demo.png)
34
 
35
+ Class: *golden retriever* (ImageNet 207) β€” JLT-B/1 at 256Γ—256, 50 Heun steps, `guidance_scale=2.9`, `noise_scale=1.0`, `torch_dtype=bfloat16`, seed 42. These checkpoints are trained and sampled at 256Γ—256 only.
36
 
37
  ## Available checkpoints
38
 
 
40
  | --- | --- | --- | --- | ---: |
41
  | JLT-B/1 | [`JLT-B-1/`](JLT-B-1/) | 256Γ—256 | FLUX.2, patch /1 | 2.9 |
42
  | JLT-L/1 | [`JLT-L-1/`](JLT-L-1/) | 256Γ—256 | FLUX.2, patch /1 | 2.9 |
43
+ | JLT-H/1 | [`JLT-H-1/`](JLT-H-1/) | 256Γ—256 | FLUX.2, patch /1 | 2.9 |
44
 
45
  ## ImageNet class labels
46
 
 
54
  ## Inference
55
 
56
  ```python
 
 
57
  import torch
58
+ from diffusers import DiffusionPipeline
59
 
60
+ pipe = DiffusionPipeline.from_pretrained(
61
+ "BiliSakura/JLT-diffusers",
62
+ subfolder="JLT-B-1", # or "JLT-L-1" / "JLT-H-1"
63
+ custom_pipeline="pipeline.py",
64
+ trust_remote_code=True,
 
 
65
  torch_dtype=torch.bfloat16,
66
  ).to("cuda")
67
 
 
75
  image.save("demo.png")
76
  ```
77
 
78
+ ## Citation
 
 
 
 
 
79
 
80
+ ```bibtex
81
+ @article{fu2026jlt,
82
+ title={{JLT}: {C}lean-{L}atent {P}rediction in {L}atent {D}iffusion {T}ransformers},
83
+ author={Fu, Funing and Wang, Tenghui and Zhou, Guanyu and Cen, Junyong and Zhu, Qichao},
84
+ journal = {arXiv preprint arXiv:2605.27102},
85
+ year={2026}
86
+ }
87
  ```