data-archetype commited on
Commit
0957ad9
·
verified ·
1 Parent(s): efe345a

dflow_2b 0.215: MOSS layout support

Browse files
MANUAL.md CHANGED
@@ -265,7 +265,8 @@ format of the MOSS-Image layout prompts.
265
 
266
  The compiled boxes are in pixels, so a compiled layout belongs to one image
267
  size: the same stored layout compiles to different numbers at 832×1216 and at
268
- 1216×832. Using a compiled layout at another size raises an error.
 
269
 
270
  Keep layouts in the stored format, which is independent of size, and let the
271
  code compile them:
@@ -278,6 +279,25 @@ code compile them:
278
  `dflow.inference.resolve_prompt`, and `dflow.layout.compile_layout` returns
279
  the compiled text if you want to inspect it.
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  ### Worked example: a jazz festival poster
282
 
283
  This layout describes an 832×1216 poster with a sun, a saxophonist and two
@@ -827,8 +847,9 @@ pipe(
827
  | `image_to_image` | An `ImageToImage`, to start from existing latents |
828
  | `callback` | A latent callback, called after each solver step |
829
 
830
- A prompt may be a plain caption, a stored layout or a compiled layout; a
831
- compiled layout must have been compiled for the requested size. The images of
 
832
  one call share the seed and differ because each gets its own noise.
833
 
834
  The result is a `DFlowOutput` with three fields: `images`, a list of PIL images
@@ -1069,18 +1090,18 @@ Encodes a plain prompt. Output: `conditioning`.
1069
  | `emphasis_encoder` | on | Also apply the weights inside the text encoder |
1070
 
1071
  For a negative prompt, add a second DFlow Text Encode node and connect it to
1072
- the guider's `negative` input. Stored layouts go to DFlow Layout Encode, which
1073
- takes the image size they are compiled for.
1074
 
1075
  ### DFlow Layout Encode
1076
 
1077
- Compiles a stored layout at the image size and encodes it. Output:
1078
  `conditioning`.
1079
 
1080
  | Input | Default | Meaning |
1081
  | --- | --- | --- |
1082
  | `text_encoder` | | From the loader |
1083
- | `layout_json` | empty | The stored layout, or an already compiled one |
1084
  | `width` | 832 | Image width the layout is for |
1085
  | `height` | 1216 | Image height the layout is for |
1086
  | `batch_size` | 1 | Copies of the prompt |
 
265
 
266
  The compiled boxes are in pixels, so a compiled layout belongs to one image
267
  size: the same stored layout compiles to different numbers at 832×1216 and at
268
+ 1216×832. A compiled layout whose boxes do not fit the image size raises an
269
+ error.
270
 
271
  Keep layouts in the stored format, which is independent of size, and let the
272
  code compile them:
 
279
  `dflow.inference.resolve_prompt`, and `dflow.layout.compile_layout` returns
280
  the compiled text if you want to inspect it.
281
 
282
+ ### MOSS-Image layouts
283
+
284
+ The model reads the compiled form, which is the layout prompt format of
285
+ [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image). MOSS-Image layouts work
286
+ wherever a stored layout does, and are converted as follows:
287
+
288
+ - **MOSS-Image layout prompts** (`bbox` in pixels from the centre,
289
+ `abs_centralized`, `yxyx`), such as the output of ComfyUI's MOSS-Image Layout
290
+ Prompt node, keep their items. Every layout the model was trained on began
291
+ with a full-canvas `panel` item, so a prompt without one gets a bare panel
292
+ (label and box only) put first. Every box must fit the image size.
293
+ - **MOSS-Image editable drafts** (`width`, `height`, `bbox` in pixels from the
294
+ top-left, `abs`, `xyxy`) are compiled the way MOSS-Image's
295
+ `compile_prompt.py` compiles them, then given the panel. The draft's `width`
296
+ and `height` must equal the image size.
297
+
298
+ In ComfyUI, give either to DFlow Layout Encode; DFlow Text Encode encodes a
299
+ MOSS-Image layout prompt exactly as written, without the panel.
300
+
301
  ### Worked example: a jazz festival poster
302
 
303
  This layout describes an 832×1216 poster with a sun, a saxophonist and two
 
847
  | `image_to_image` | An `ImageToImage`, to start from existing latents |
848
  | `callback` | A latent callback, called after each solver step |
849
 
850
+ A prompt may be a plain caption or a layout in any form that
851
+ [JSON layouts](#json-layouts) describes; a compiled layout's boxes must fit the
852
+ requested size. The images of
853
  one call share the seed and differ because each gets its own noise.
854
 
855
  The result is a `DFlowOutput` with three fields: `images`, a list of PIL images
 
1090
  | `emphasis_encoder` | on | Also apply the weights inside the text encoder |
1091
 
1092
  For a negative prompt, add a second DFlow Text Encode node and connect it to
1093
+ the guider's `negative` input. Stored layouts and MOSS-Image drafts go to DFlow
1094
+ Layout Encode, which takes the image size they are compiled for.
1095
 
1096
  ### DFlow Layout Encode
1097
 
1098
+ Compiles a layout at the image size and encodes it. Output:
1099
  `conditioning`.
1100
 
1101
  | Input | Default | Meaning |
1102
  | --- | --- | --- |
1103
  | `text_encoder` | | From the loader |
1104
+ | `layout_json` | empty | A stored or compiled layout, or a MOSS-Image layout prompt or draft |
1105
  | `width` | 832 | Image width the layout is for |
1106
  | `height` | 1216 | Image height the layout is for |
1107
  | `batch_size` | 1 | Copies of the prompt |
README.md CHANGED
@@ -17,15 +17,16 @@ base_model:
17
  # dflow_2b
18
 
19
  > [!WARNING]
20
- > **Preview, version 0.21.** The model is still training, so checkpoints and
21
  > behaviour will change between releases. Generations are still uneven, expect
22
  > some seed hunting.
23
 
24
  dflow_2b is an indie text-to-image model, trained from scratch on a single GPU,
25
  mostly on photographs and classical art.
26
 
27
- It takes ordinary captions, and also JSON layout captions (the same format as
28
- [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image)).
 
29
 
30
  The package contains the weights, the `dflow` inference code and ComfyUI nodes.
31
 
@@ -132,6 +133,7 @@ elements carry the exact string to render:
132
  ```
133
 
134
  Use it as the prompt in Python, or paste it into the DFlow Layout Encode node.
 
135
  The [manual](MANUAL.md#json-layouts) covers every field and works through a
136
  full poster.
137
 
@@ -169,6 +171,6 @@ Third-party material is listed in [`ATTRIBUTION.md`](ATTRIBUTION.md).
169
  author = {{Data Archetype}},
170
  year = {2026},
171
  url = {https://huggingface.co/data-archetype/dflow_2b},
172
- note = {Preview release, version 0.21}
173
  }
174
  ```
 
17
  # dflow_2b
18
 
19
  > [!WARNING]
20
+ > **Preview, version 0.215.** The model is still training, so checkpoints and
21
  > behaviour will change between releases. Generations are still uneven, expect
22
  > some seed hunting.
23
 
24
  dflow_2b is an indie text-to-image model, trained from scratch on a single GPU,
25
  mostly on photographs and classical art.
26
 
27
+ It takes ordinary captions and JSON layout captions. The layout format is close
28
+ to [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image)'s, and MOSS-Image
29
+ layouts are converted internally.
30
 
31
  The package contains the weights, the `dflow` inference code and ComfyUI nodes.
32
 
 
133
  ```
134
 
135
  Use it as the prompt in Python, or paste it into the DFlow Layout Encode node.
136
+ MOSS-Image layout prompts and editable drafts go in the same places.
137
  The [manual](MANUAL.md#json-layouts) covers every field and works through a
138
  full poster.
139
 
 
171
  author = {{Data Archetype}},
172
  year = {2026},
173
  url = {https://huggingface.co/data-archetype/dflow_2b},
174
+ note = {Preview release, version 0.215}
175
  }
176
  ```
RELEASES.md CHANGED
@@ -3,6 +3,12 @@
3
  [Model card](README.md) · [Manual](MANUAL.md) ·
4
  [Technical report](TECHNICAL_REPORT.md) · [Example gallery](GALLERY.md)
5
 
 
 
 
 
 
 
6
  ## 0.21
7
 
8
  Checkpoint update: the EMA at training step 583,000.
 
3
  [Model card](README.md) · [Manual](MANUAL.md) ·
4
  [Technical report](TECHNICAL_REPORT.md) · [Example gallery](GALLERY.md)
5
 
6
+ ## 0.215
7
+
8
+ Same weights as 0.21. MOSS-Image layout prompts and editable drafts now work
9
+ as given: they are converted internally, and a full-canvas panel is added to
10
+ prompts that have none, as in every layout the model was trained on.
11
+
12
  ## 0.21
13
 
14
  Checkpoint update: the EMA at training step 583,000.
comfyui/nodes.py CHANGED
@@ -46,7 +46,7 @@ from ..dflow.inference import (
46
  GenerationSettings,
47
  SamplingSettings,
48
  )
49
- from ..dflow.layout import compile_layout, is_compiled_layout, is_stored_layout
50
  from ..dflow.prompt_emphasis import EmphasisMapping, EmphasisSettings
51
  from ..dflow.schedules import ScheduleKind, TimeSchedule
52
  from ..dflow.solvers import Solver
@@ -181,8 +181,10 @@ def _encode(
181
  encoder: DFlowTextEncoderHandle,
182
  prompts: tuple[str, ...],
183
  emphasis: EmphasisSettings | None,
 
184
  ) -> DFlowConditioning:
185
- """Encode and refine a prompt batch (as ``DFlowEngine.prepare_texts``)."""
 
186
 
187
  engine = encoder.model.engine
188
  with torch.inference_mode():
@@ -190,7 +192,11 @@ def _encode(
190
  engine.text_encoder.encode(list(prompts), emphasis=emphasis)
191
  )
192
  return DFlowConditioning(
193
- model=encoder.model, prompts=prompts, text=text, emphasis=emphasis
 
 
 
 
194
  )
195
 
196
 
@@ -320,7 +326,8 @@ class DFlowTextEncode:
320
  DESCRIPTION = (
321
  "Plain prompts and compiled layout prompts. (phrase:weight) markup "
322
  "weights a phrase when emphasis is on; quoted text is spelled out "
323
- "character by character. Use DFlow Layout Encode for stored layouts."
 
324
  )
325
  RETURN_TYPES = ("DFLOW_CONDITIONING",)
326
  RETURN_NAMES = ("conditioning",)
@@ -365,13 +372,14 @@ class DFlowTextEncode:
365
  """Encode ``batch_size`` copies of the prompt.
366
 
367
  Raises:
368
- ValueError: For a stored layout (it needs the image size).
 
369
  """
370
 
371
- if is_stored_layout(text):
372
  raise ValueError(
373
- "This is a stored layout; use DFlow Layout Encode, which compiles "
374
- "it at the image size."
375
  )
376
  settings = (
377
  EmphasisSettings(
@@ -382,15 +390,18 @@ class DFlowTextEncode:
382
  if emphasis
383
  else None
384
  )
385
- return (_encode(text_encoder, (text,) * batch_size, settings),)
386
 
387
 
388
  class DFlowLayoutEncode:
389
- """Compile a stored layout at the image size and encode it."""
 
390
 
391
  DESCRIPTION = (
392
- "Takes the stored layout JSON (summary, frame, items with box_2d on a "
393
- "0-1000 grid) or a compiled layout. width and height must match the "
 
 
394
  "latent; the guider checks it."
395
  )
396
  RETURN_TYPES = ("DFLOW_CONDITIONING",)
@@ -421,19 +432,19 @@ class DFlowLayoutEncode:
421
  height: int,
422
  batch_size: int,
423
  ) -> tuple[DFlowConditioning]:
424
- """Compile (or size-check) the layout and encode it verbatim.
425
 
426
  Raises:
427
  ValueError: If the text is not a layout, or for a malformed layout.
428
  """
429
 
430
- if not (is_stored_layout(layout_json) or is_compiled_layout(layout_json)):
431
  raise ValueError(
432
  "layout_json is not a layout (a JSON object with summary and "
433
  "items); use DFlow Text Encode for plain prompts."
434
  )
435
  compiled = compile_layout(layout_json, width, height)
436
- return (_encode(text_encoder, (compiled,) * batch_size, None),)
437
 
438
 
439
  class DFlowGuiderNode:
 
46
  GenerationSettings,
47
  SamplingSettings,
48
  )
49
+ from ..dflow.layout import compile_layout, is_compiled_layout, is_uncompiled_layout
50
  from ..dflow.prompt_emphasis import EmphasisMapping, EmphasisSettings
51
  from ..dflow.schedules import ScheduleKind, TimeSchedule
52
  from ..dflow.solvers import Solver
 
181
  encoder: DFlowTextEncoderHandle,
182
  prompts: tuple[str, ...],
183
  emphasis: EmphasisSettings | None,
184
+ layout_size: tuple[int, int] | None,
185
  ) -> DFlowConditioning:
186
+ """Encode and refine a prompt batch (as ``DFlowEngine.prepare_texts``);
187
+ ``layout_size`` is the size a layout was compiled for, if any."""
188
 
189
  engine = encoder.model.engine
190
  with torch.inference_mode():
 
192
  engine.text_encoder.encode(list(prompts), emphasis=emphasis)
193
  )
194
  return DFlowConditioning(
195
+ model=encoder.model,
196
+ prompts=prompts,
197
+ text=text,
198
+ emphasis=emphasis,
199
+ layout_size=layout_size,
200
  )
201
 
202
 
 
326
  DESCRIPTION = (
327
  "Plain prompts and compiled layout prompts. (phrase:weight) markup "
328
  "weights a phrase when emphasis is on; quoted text is spelled out "
329
+ "character by character. Compiled layout prompts are encoded as "
330
+ "written; use DFlow Layout Encode for stored layouts and MOSS drafts."
331
  )
332
  RETURN_TYPES = ("DFLOW_CONDITIONING",)
333
  RETURN_NAMES = ("conditioning",)
 
372
  """Encode ``batch_size`` copies of the prompt.
373
 
374
  Raises:
375
+ ValueError: For a stored layout or MOSS draft (they need the
376
+ image size).
377
  """
378
 
379
+ if is_uncompiled_layout(text):
380
  raise ValueError(
381
+ "This layout (a stored layout or a MOSS draft) must be compiled "
382
+ "at the image size; use DFlow Layout Encode."
383
  )
384
  settings = (
385
  EmphasisSettings(
 
390
  if emphasis
391
  else None
392
  )
393
+ return (_encode(text_encoder, (text,) * batch_size, settings, None),)
394
 
395
 
396
  class DFlowLayoutEncode:
397
+ """Compile a layout (stored, compiled or MOSS-Image) at the image size and
398
+ encode it."""
399
 
400
  DESCRIPTION = (
401
+ "Takes a stored layout (summary, frame, items with box_2d on a 0-1000 "
402
+ "grid), a MOSS-Image layout prompt or a MOSS-Image editable draft, "
403
+ "and compiles it at width x height; a full-canvas panel is added "
404
+ "first when the layout has none. width and height must match the "
405
  "latent; the guider checks it."
406
  )
407
  RETURN_TYPES = ("DFLOW_CONDITIONING",)
 
432
  height: int,
433
  batch_size: int,
434
  ) -> tuple[DFlowConditioning]:
435
+ """Compile the layout at the image size and encode the result.
436
 
437
  Raises:
438
  ValueError: If the text is not a layout, or for a malformed layout.
439
  """
440
 
441
+ if not is_compiled_layout(layout_json):
442
  raise ValueError(
443
  "layout_json is not a layout (a JSON object with summary and "
444
  "items); use DFlow Text Encode for plain prompts."
445
  )
446
  compiled = compile_layout(layout_json, width, height)
447
+ return (_encode(text_encoder, (compiled,) * batch_size, None, (width, height)),)
448
 
449
 
450
  class DFlowGuiderNode:
comfyui/sampling.py CHANGED
@@ -36,7 +36,7 @@ from ..dflow.guidance import (
36
  build_guidance_plan,
37
  check_three_quarter_size,
38
  )
39
- from ..dflow.layout import compile_layout, is_compiled_layout
40
  from ..dflow.modeling import PreparedText, self_attention_gain_tensor
41
  from ..dflow.schedules import FINITE_NOISY_ENDPOINT_EPSILON
42
  from ..dflow.solvers import solve, solver_is_stochastic
@@ -225,6 +225,13 @@ class DFlowGuider:
225
  ]
226
  )
227
  for conditioning in conditionings:
 
 
 
 
 
 
 
228
  for prompt in conditioning.prompts:
229
  if is_compiled_layout(prompt):
230
  compile_layout(prompt, width, height)
 
36
  build_guidance_plan,
37
  check_three_quarter_size,
38
  )
39
+ from ..dflow.layout import LayoutSizeMismatchError, compile_layout, is_compiled_layout
40
  from ..dflow.modeling import PreparedText, self_attention_gain_tensor
41
  from ..dflow.schedules import FINITE_NOISY_ENDPOINT_EPSILON
42
  from ..dflow.solvers import solve, solver_is_stochastic
 
225
  ]
226
  )
227
  for conditioning in conditionings:
228
+ if conditioning.layout_size not in (None, (width, height)):
229
+ layout_width, layout_height = conditioning.layout_size
230
+ raise LayoutSizeMismatchError(
231
+ f"DFlow Layout Encode compiled the layout for "
232
+ f"{layout_width}x{layout_height}; the latent is "
233
+ f"{width}x{height}. Set its width and height to the latent's."
234
+ )
235
  for prompt in conditioning.prompts:
236
  if is_compiled_layout(prompt):
237
  compile_layout(prompt, width, height)
comfyui/types.py CHANGED
@@ -107,12 +107,15 @@ class DFlowConditioning:
107
  their compiled form).
108
  text: The refined text tokens.
109
  emphasis: The prompt-emphasis settings used, or None for verbatim.
 
 
110
  """
111
 
112
  model: DFlowModelHandle
113
  prompts: tuple[str, ...]
114
  text: PreparedText
115
  emphasis: EmphasisSettings | None
 
116
 
117
  @property
118
  def batch(self) -> int:
 
107
  their compiled form).
108
  text: The refined text tokens.
109
  emphasis: The prompt-emphasis settings used, or None for verbatim.
110
+ layout_size: The ``(width, height)`` DFlow Layout Encode compiled the
111
+ layout for (the guider requires the latent's size), or None.
112
  """
113
 
114
  model: DFlowModelHandle
115
  prompts: tuple[str, ...]
116
  text: PreparedText
117
  emphasis: EmphasisSettings | None
118
+ layout_size: tuple[int, int] | None
119
 
120
  @property
121
  def batch(self) -> int:
dflow/layout.py CHANGED
@@ -12,6 +12,15 @@ The model was trained on the compiled form, which depends on the image size:
12
  the frame becomes a full-canvas ``panel`` item and every box becomes integer
13
  pixels centred on the image centre (``abs_centralized``, ``yxyx``). Optional
14
  fields may be left out; training dropped them at random.
 
 
 
 
 
 
 
 
 
15
  """
16
 
17
  from __future__ import annotations
@@ -28,7 +37,7 @@ __all__ = [
28
  "LayoutSizeMismatchError",
29
  "compile_layout",
30
  "is_compiled_layout",
31
- "is_stored_layout",
32
  "panel_box",
33
  ]
34
 
@@ -44,6 +53,12 @@ _ITEM_KEYS = frozenset({"label", "box_2d", "text", *_ENTRY_FIELDS})
44
  _COORD_SPACE = "abs_centralized"
45
  _BOX_FORMAT = "yxyx"
46
  _COMPILED_KEYS = frozenset({"summary", "items", "bbox_coord_space", "bbox_format"})
 
 
 
 
 
 
47
  # Top-level keys every JSON prompt has; the text encoder tokenizes such prompts
48
  # as structured JSON (character tokens for visible text only).
49
  _JSON_PROMPT_KEYS = frozenset({"summary", "items"})
@@ -58,6 +73,10 @@ class LayoutLabel(StrEnum):
58
  PANEL = "panel"
59
 
60
 
 
 
 
 
61
  class LayoutError(ValueError):
62
  """A layout is malformed."""
63
 
@@ -88,19 +107,23 @@ def is_compiled_layout(text: str) -> bool:
88
 
89
  The text encoder tokenizes such prompts as structured JSON and never parses
90
  them for emphasis markup, exactly as in training. A stored (uncompiled)
91
- layout also passes this test; ``is_stored_layout`` tells them apart.
92
  """
93
 
94
  parsed = _json_object(text)
95
  return parsed is not None and set(parsed) >= _JSON_PROMPT_KEYS
96
 
97
 
98
- def is_stored_layout(text: str) -> bool:
99
  """Whether ``text`` is a stored layout (``summary``, ``frame``, ``items``)
100
- that still needs ``compile_layout`` before it can be encoded."""
 
101
 
102
  parsed = _json_object(text)
103
- return parsed is not None and set(parsed) == _STORED_KEYS
 
 
 
104
 
105
 
106
  def panel_box(width: int, height: int) -> list[int]:
@@ -296,56 +319,230 @@ def _compile_stored(layout: Mapping[str, object], *, width: int, height: int) ->
296
  return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))
297
 
298
 
299
- def _compiled_size(items: object) -> tuple[int, int] | None:
300
- """Return the ``(width, height)`` a compiled prompt's panel encodes, or None."""
301
 
302
- match items:
303
- case [{"label": "panel", "bbox": list() as box}, *_]:
304
- try:
305
- y0, x0, y1, x1 = _four_ints(box, where="panel bbox")
306
- except LayoutError:
307
- return None
308
- width, height = x1 - x0, y1 - y0
309
- if width <= 0 or height <= 0 or box != panel_box(width, height):
310
- return None
311
- return width, height
312
  case _:
313
- return None
 
 
 
 
 
 
 
 
 
 
314
 
 
 
 
 
 
 
 
 
 
315
 
316
- def _check_compiled(parsed: Mapping[str, object], *, width: int, height: int) -> None:
317
- """Check a compiled prompt's format and that its panel matches the size.
 
 
 
 
318
 
319
  Raises:
320
- LayoutSizeMismatchError: If the panel box is for another size.
321
  LayoutError: If the prompt is not a compiled layout.
322
  """
323
 
324
- if set(parsed) != _COMPILED_KEYS:
325
  raise LayoutError(
326
  "A compiled layout needs exactly the keys summary, items, "
327
- f"bbox_coord_space and bbox_format; got {sorted(parsed)}."
328
  )
329
  if (
330
- parsed["bbox_coord_space"] != _COORD_SPACE
331
- or parsed["bbox_format"] != _BOX_FORMAT
332
  ):
333
  raise LayoutError(
334
  f"A compiled layout must use bbox_coord_space={_COORD_SPACE!r} and "
335
  f"bbox_format={_BOX_FORMAT!r}."
336
  )
337
- size = _compiled_size(parsed["items"])
338
- if size is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  raise LayoutError(
340
- "A compiled layout's first item must be the full-canvas panel with an "
341
- "integer bbox."
342
  )
343
- if size != (width, height):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  raise LayoutSizeMismatchError(
345
- f"This layout prompt was compiled for {size[0]}x{size[1]} "
346
- f"(width x height); the image is {width}x{height}. Compile the "
347
- "stored layout again at the image size."
348
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
 
351
  def compile_layout(
@@ -354,18 +551,20 @@ def compile_layout(
354
  """Return the layout prompt the model reads for a ``width`` x ``height`` image.
355
 
356
  Args:
357
- layout_json: A stored layout (JSON text or a parsed mapping), or an
358
- already compiled prompt (JSON text only), which is returned
359
- verbatim after its panel box is checked against the size.
360
  width: Image width in pixels.
361
  height: Image height in pixels.
362
 
363
  Returns:
364
- The compiled prompt: one-line JSON, byte-identical to the training-time
365
- compile of the same stored layout at this size.
 
 
366
 
367
  Raises:
368
- LayoutSizeMismatchError: If a compiled prompt is for another size.
369
  LayoutError: If the layout is malformed or the size is not positive.
370
  """
371
 
@@ -375,13 +574,8 @@ def compile_layout(
375
  parsed = _json_object(text)
376
  if parsed is None:
377
  raise LayoutError("The layout is not a JSON object.")
378
- # Only compiled prompts carry a coordinate space; anything else is
379
- # read as a stored layout, whose own checks name a bad key.
380
- if "bbox_coord_space" not in parsed:
381
- return _compile_stored(parsed, width=width, height=height)
382
- _check_compiled(parsed, width=width, height=height)
383
- return text
384
  case Mapping() as layout:
385
- return _compile_stored(layout, width=width, height=height)
386
  case _:
387
  raise TypeError("layout_json must be JSON text or a mapping.")
 
12
  the frame becomes a full-canvas ``panel`` item and every box becomes integer
13
  pixels centred on the image centre (``abs_centralized``, ``yxyx``). Optional
14
  fields may be left out; training dropped them at random.
15
+
16
+ MOSS-Image layouts are accepted too and converted to that form:
17
+
18
+ - a model-facing MOSS prompt (``bbox`` in ``abs_centralized`` ``yxyx`` pixels)
19
+ keeps its items, with a bare full-canvas ``panel`` put first when it has
20
+ none (every training layout had one);
21
+ - a MOSS editable draft (``width``, ``height``, ``bbox`` in ``abs`` ``xyxy``
22
+ pixels from the top-left) is compiled as MOSS's ``compile_prompt.py`` does,
23
+ then given the panel the same way.
24
  """
25
 
26
  from __future__ import annotations
 
37
  "LayoutSizeMismatchError",
38
  "compile_layout",
39
  "is_compiled_layout",
40
+ "is_uncompiled_layout",
41
  "panel_box",
42
  ]
43
 
 
53
  _COORD_SPACE = "abs_centralized"
54
  _BOX_FORMAT = "yxyx"
55
  _COMPILED_KEYS = frozenset({"summary", "items", "bbox_coord_space", "bbox_format"})
56
+ # MOSS-Image editable drafts: top-left pixel boxes on a canvas they name.
57
+ _DRAFT_COORD_SPACE = "abs"
58
+ _DRAFT_BOX_FORMAT = "xyxy"
59
+ _DRAFT_KEYS = frozenset({"width", "height", *_COMPILED_KEYS})
60
+ _DRAFT_SUMMARY_KEYS = frozenset({*_SUMMARY_KEYS, "palette"})
61
+ _DRAFT_ITEM_KEYS = frozenset({"label", "bbox", "text", *_ENTRY_FIELDS})
62
  # Top-level keys every JSON prompt has; the text encoder tokenizes such prompts
63
  # as structured JSON (character tokens for visible text only).
64
  _JSON_PROMPT_KEYS = frozenset({"summary", "items"})
 
73
  PANEL = "panel"
74
 
75
 
76
+ # Labels a MOSS editable draft may use (its compiler adds no panel).
77
+ _DRAFT_LABELS = frozenset({LayoutLabel.CHARACTER, LayoutLabel.OBJECT, LayoutLabel.TEXT})
78
+
79
+
80
  class LayoutError(ValueError):
81
  """A layout is malformed."""
82
 
 
107
 
108
  The text encoder tokenizes such prompts as structured JSON and never parses
109
  them for emphasis markup, exactly as in training. A stored (uncompiled)
110
+ layout or a MOSS draft also passes; ``is_uncompiled_layout`` tells them apart.
111
  """
112
 
113
  parsed = _json_object(text)
114
  return parsed is not None and set(parsed) >= _JSON_PROMPT_KEYS
115
 
116
 
117
+ def is_uncompiled_layout(text: str) -> bool:
118
  """Whether ``text`` is a stored layout (``summary``, ``frame``, ``items``)
119
+ or a MOSS editable draft (``bbox_coord_space`` ``abs``), either of which
120
+ needs ``compile_layout`` at the image size before it can be encoded."""
121
 
122
  parsed = _json_object(text)
123
+ return parsed is not None and (
124
+ set(parsed) == _STORED_KEYS
125
+ or parsed.get("bbox_coord_space") == _DRAFT_COORD_SPACE
126
+ )
127
 
128
 
129
  def panel_box(width: int, height: int) -> list[int]:
 
319
  return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))
320
 
321
 
322
+ def _require_list(value: object, *, where: str) -> list[object]:
323
+ """Return ``value`` as a JSON list.
324
 
325
+ Raises:
326
+ LayoutError: If it is not one.
327
+ """
328
+
329
+ match value:
330
+ case list():
331
+ return value
 
 
 
332
  case _:
333
+ raise LayoutError(f"{where} must be a JSON list.")
334
+
335
+
336
+ def _check_canvas_box(box: object, *, width: int, height: int, where: str) -> None:
337
+ """Check that a compiled (``abs_centralized``, ``yxyx``) box lies on the
338
+ ``width`` x ``height`` canvas.
339
+
340
+ Raises:
341
+ LayoutSizeMismatchError: If it leaves the canvas.
342
+ LayoutError: If it is not four ordered integers.
343
+ """
344
 
345
+ y0, x0, y1, x1 = _four_ints(box, where=f"{where}.bbox")
346
+ if not (y0 < y1 and x0 < x1):
347
+ raise LayoutError(f"{where}.bbox {box!r} must be [y0, x0, y1, x1], ordered.")
348
+ top, left, bottom, right = panel_box(width, height)
349
+ if y0 < top or x0 < left or y1 > bottom or x1 > right:
350
+ raise LayoutSizeMismatchError(
351
+ f"{where}.bbox {box!r} leaves the {width}x{height} canvas "
352
+ f"[{top}, {left}, {bottom}, {right}]: the layout is for a larger image."
353
+ )
354
 
355
+
356
+ def _checked_compiled(
357
+ layout: Mapping[str, object], *, width: int, height: int
358
+ ) -> list[Mapping[str, object]]:
359
+ """Check a compiled prompt (this package's or a MOSS-Image one) against
360
+ the image size and return its items.
361
 
362
  Raises:
363
+ LayoutSizeMismatchError: If a box leaves the canvas.
364
  LayoutError: If the prompt is not a compiled layout.
365
  """
366
 
367
+ if set(layout) != _COMPILED_KEYS:
368
  raise LayoutError(
369
  "A compiled layout needs exactly the keys summary, items, "
370
+ f"bbox_coord_space and bbox_format; got {sorted(layout)}."
371
  )
372
  if (
373
+ layout["bbox_coord_space"] != _COORD_SPACE
374
+ or layout["bbox_format"] != _BOX_FORMAT
375
  ):
376
  raise LayoutError(
377
  f"A compiled layout must use bbox_coord_space={_COORD_SPACE!r} and "
378
  f"bbox_format={_BOX_FORMAT!r}."
379
  )
380
+ raw_items = _require_list(layout["items"], where="items")
381
+ items = [
382
+ _require_object(raw, where=f"items[{p}]") for p, raw in enumerate(raw_items)
383
+ ]
384
+ for pos, item in enumerate(items):
385
+ if "bbox" not in item:
386
+ raise LayoutError(f"items[{pos}] needs a bbox [y0, x0, y1, x1].")
387
+ _check_canvas_box(
388
+ item["bbox"], width=width, height=height, where=f"items[{pos}]"
389
+ )
390
+ return items
391
+
392
+
393
+ def _with_panel(
394
+ summary: Mapping[str, object],
395
+ items: list[Mapping[str, object]],
396
+ *,
397
+ width: int,
398
+ height: int,
399
+ ) -> str:
400
+ """Serialize a compiled prompt as one-line JSON, with a bare full-canvas
401
+ ``panel`` put first when the first item is not a panel."""
402
+
403
+ if not items or items[0].get("label") != LayoutLabel.PANEL:
404
+ items = [
405
+ {"label": LayoutLabel.PANEL.value, "bbox": panel_box(width, height)},
406
+ *items,
407
+ ]
408
+ prompt = {
409
+ "summary": dict(summary),
410
+ "items": [dict(item) for item in items],
411
+ "bbox_coord_space": _COORD_SPACE,
412
+ "bbox_format": _BOX_FORMAT,
413
+ }
414
+ return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))
415
+
416
+
417
+ def _finite_number(value: object) -> bool:
418
+ """Whether ``value`` is a finite int or float (booleans excluded)."""
419
+
420
+ match value:
421
+ case bool():
422
+ return False
423
+ case int():
424
+ return True
425
+ case float():
426
+ return math.isfinite(value)
427
+ case _:
428
+ return False
429
+
430
+
431
+ def _draft_box(box: object, *, width: int, height: int, where: str) -> list[int]:
432
+ """Return a MOSS draft box (``xyxy`` pixels from the top-left) as centred
433
+ ``yxyx`` pixels, as MOSS's ``compile_prompt.py`` does: min edges floored
434
+ and max edges ceiled after rounding to 9 decimals, then shifted by
435
+ ``height // 2`` / ``width // 2``.
436
+
437
+ Raises:
438
+ LayoutError: If it is not four ordered finite numbers on the canvas.
439
+ """
440
+
441
+ match box:
442
+ case list() if len(box) == 4 and all(_finite_number(v) for v in box):
443
+ x0, y0, x1, y1 = (float(v) for v in box)
444
+ case _:
445
+ raise LayoutError(f"{where}.bbox must be four finite numbers, got {box!r}.")
446
+ if not (0 <= x0 < x1 <= width and 0 <= y0 < y1 <= height):
447
+ raise LayoutError(
448
+ f"{where}.bbox {box!r} must be [x0, y0, x1, y1] inside the "
449
+ f"{width}x{height} canvas."
450
+ )
451
+ return [
452
+ math.floor(round(y0, _BOX_EDGE_DECIMALS)) - height // 2,
453
+ math.floor(round(x0, _BOX_EDGE_DECIMALS)) - width // 2,
454
+ math.ceil(round(y1, _BOX_EDGE_DECIMALS)) - height // 2,
455
+ math.ceil(round(x1, _BOX_EDGE_DECIMALS)) - width // 2,
456
+ ]
457
+
458
+
459
+ def _draft_summary(value: object) -> Mapping[str, object]:
460
+ """Return a MOSS draft's checked ``summary`` (it may carry a palette)."""
461
+
462
+ summary = _require_object(value, where="summary")
463
+ _require_keys(summary, allowed=_DRAFT_SUMMARY_KEYS, where="summary")
464
+ for key in ("meta", "palette"):
465
+ if key in summary:
466
+ _require_string_list(summary[key], where=f"summary.{key}")
467
+ for key in ("canvas", "caption"):
468
+ if key in summary:
469
+ _require_string(summary[key], where=f"summary.{key}")
470
+ return summary
471
+
472
+
473
+ def _draft_item(
474
+ raw: object, *, width: int, height: int, where: str
475
+ ) -> dict[str, object]:
476
+ """Return a MOSS draft item with its box compiled, keys in draft order."""
477
+
478
+ item = _require_object(raw, where=where)
479
+ _require_keys(item, allowed=_DRAFT_ITEM_KEYS, where=where)
480
+ if item.get("label") not in _DRAFT_LABELS:
481
  raise LayoutError(
482
+ f"{where}.label must be one of {sorted(_DRAFT_LABELS)}, "
483
+ f"got {item.get('label')!r}."
484
  )
485
+ if "bbox" not in item:
486
+ raise LayoutError(f"{where} needs a bbox [x0, y0, x1, y1] in pixels.")
487
+ if item["label"] == LayoutLabel.TEXT and "text" not in item:
488
+ raise LayoutError(f"{where} is a text item and needs its exact 'text'.")
489
+ if "text" in item:
490
+ _require_string(item["text"], where=f"{where}.text")
491
+ _validated_entry_fields(item, where=where)
492
+ return {
493
+ key: _draft_box(value, width=width, height=height, where=where)
494
+ if key == "bbox"
495
+ else value
496
+ for key, value in item.items()
497
+ }
498
+
499
+
500
+ def _compile_draft(layout: Mapping[str, object], *, width: int, height: int) -> str:
501
+ """Compile a MOSS-Image editable draft at ``width`` x ``height``.
502
+
503
+ Raises:
504
+ LayoutSizeMismatchError: If the draft is for another size.
505
+ LayoutError: If the draft is malformed.
506
+ """
507
+
508
+ if set(layout) != _DRAFT_KEYS:
509
+ raise LayoutError(
510
+ f"A MOSS draft needs exactly the keys {sorted(_DRAFT_KEYS)}; "
511
+ f"got {sorted(layout)}."
512
+ )
513
+ if layout["bbox_format"] != _DRAFT_BOX_FORMAT:
514
+ raise LayoutError(f"A MOSS draft must use bbox_format={_DRAFT_BOX_FORMAT!r}.")
515
+ if (layout["width"], layout["height"]) != (width, height):
516
  raise LayoutSizeMismatchError(
517
+ f"This MOSS draft is for {layout['width']}x{layout['height']} "
518
+ f"(width x height); the image is {width}x{height}."
 
519
  )
520
+ summary = _draft_summary(layout["summary"])
521
+ raw_items = _require_list(layout["items"], where="items")
522
+ items: list[Mapping[str, object]] = [
523
+ _draft_item(raw, width=width, height=height, where=f"items[{pos}]")
524
+ for pos, raw in enumerate(raw_items)
525
+ ]
526
+ return _with_panel(summary, items, width=width, height=height)
527
+
528
+
529
+ def _compile_parsed(layout: Mapping[str, object], *, width: int, height: int) -> str:
530
+ """Compile a parsed layout of any accepted kind (see the module docstring).
531
+
532
+ Raises:
533
+ LayoutSizeMismatchError: If the layout is for another size.
534
+ LayoutError: If the layout is malformed.
535
+ """
536
+
537
+ match layout.get("bbox_coord_space"):
538
+ case None:
539
+ return _compile_stored(layout, width=width, height=height)
540
+ case str() as space if space == _DRAFT_COORD_SPACE:
541
+ return _compile_draft(layout, width=width, height=height)
542
+ case _:
543
+ items = _checked_compiled(layout, width=width, height=height)
544
+ summary = _require_object(layout["summary"], where="summary")
545
+ return _with_panel(summary, items, width=width, height=height)
546
 
547
 
548
  def compile_layout(
 
551
  """Return the layout prompt the model reads for a ``width`` x ``height`` image.
552
 
553
  Args:
554
+ layout_json: A stored layout, a MOSS-Image editable draft or a compiled
555
+ prompt (this package's or a MOSS-Image one), as JSON text or a
556
+ parsed mapping.
557
  width: Image width in pixels.
558
  height: Image height in pixels.
559
 
560
  Returns:
561
+ The compiled prompt as one-line JSON. A stored layout compiles
562
+ byte-identically to the training-time compile, and this package's
563
+ compiled prompts come back unchanged; any other prompt keeps its items
564
+ and gets a bare full-canvas panel first if it has none.
565
 
566
  Raises:
567
+ LayoutSizeMismatchError: If the layout is for another size.
568
  LayoutError: If the layout is malformed or the size is not positive.
569
  """
570
 
 
574
  parsed = _json_object(text)
575
  if parsed is None:
576
  raise LayoutError("The layout is not a JSON object.")
577
+ return _compile_parsed(parsed, width=width, height=height)
 
 
 
 
 
578
  case Mapping() as layout:
579
+ return _compile_parsed(layout, width=width, height=height)
580
  case _:
581
  raise TypeError("layout_json must be JSON text or a mapping.")
dflow/text_conditioning.py CHANGED
@@ -28,7 +28,7 @@ import torch
28
  import torch.nn.functional as F
29
  from torch import Tensor, nn
30
 
31
- from .layout import is_compiled_layout, is_stored_layout
32
  from .prompt_emphasis import (
33
  EmphasisSettings,
34
  TokenEmphasis,
@@ -233,16 +233,16 @@ class DFlowTextEncoder(nn.Module):
233
  """Tokenize one prompt and map its emphasis onto the tokens.
234
 
235
  Raises:
236
- ValueError: For a stored (uncompiled) layout.
237
  PromptTooLongError: If the prompt is too long.
238
  """
239
 
240
  if not prompt.strip():
241
  return _PreparedPrompt(ids=None, emphasis=None)
242
  if is_compiled_layout(prompt):
243
- if is_stored_layout(prompt):
244
  raise ValueError(
245
- "This is a stored layout; compile it at the image size first "
246
  "with dflow.layout.compile_layout(layout, width, height)."
247
  )
248
  return _PreparedPrompt(
 
28
  import torch.nn.functional as F
29
  from torch import Tensor, nn
30
 
31
+ from .layout import is_compiled_layout, is_uncompiled_layout
32
  from .prompt_emphasis import (
33
  EmphasisSettings,
34
  TokenEmphasis,
 
233
  """Tokenize one prompt and map its emphasis onto the tokens.
234
 
235
  Raises:
236
+ ValueError: For a stored layout or MOSS draft (uncompiled).
237
  PromptTooLongError: If the prompt is too long.
238
  """
239
 
240
  if not prompt.strip():
241
  return _PreparedPrompt(ids=None, emphasis=None)
242
  if is_compiled_layout(prompt):
243
+ if is_uncompiled_layout(prompt):
244
  raise ValueError(
245
+ "This layout is not compiled; compile it at the image size first "
246
  "with dflow.layout.compile_layout(layout, width, height)."
247
  )
248
  return _PreparedPrompt(
dflow/version.py CHANGED
@@ -1,4 +1,4 @@
1
  """Package and model version."""
2
 
3
- __version__ = "0.21.0"
4
- MODEL_VERSION = "0.21"
 
1
  """Package and model version."""
2
 
3
+ __version__ = "0.215.0"
4
+ MODEL_VERSION = "0.215"
release.json CHANGED
@@ -5,5 +5,5 @@
5
  "tensor_count": 468,
6
  "text_encoder_repository": "google/t5gemma-2-270m-270m",
7
  "vae_repository": "data-archetype/dinac3_96",
8
- "version": "0.21"
9
  }
 
5
  "tensor_count": 468,
6
  "text_encoder_repository": "google/t5gemma-2-270m-270m",
7
  "vae_repository": "data-archetype/dinac3_96",
8
+ "version": "0.215"
9
  }