Model Card for Coarse-to-Fine¶
This package ports Coarse-to-Fine, an AAAI 2022 hierarchy-first layout generator, into a 🤗transformers-style package that returns the shared layout schema.
Model Details¶
Model Description¶
Coarse-to-Fine generates page or UI layouts through a hierarchy-aware transformers model: it predicts coarse group structure before refining element boxes and labels for RICO25 or PubLayNet. It supports unconditional local inference from converted checkpoints and exposes hierarchy traces through intermediates when requested. Public outputs use normalized center xywh boxes in [0, 1], dataset-local integer labels, a valid-element mask, and id2label.
- Developed by: Zhaoyun Jiang et al.
- Shared by: creative-graphic-design.
- Model type: content-agnostic; task: single-task; conditioning: unconditional.
- Language(s) (NLP): not applicable.
- License: MIT.
Model Sources¶
- Repository: Microsoft LayoutGeneration Coarse-to-Fine
- Paper: AAAI paper page
Supported Checkpoints¶
| Checkpoint | Hub ID | Status |
|---|---|---|
| RICO25 | creative-graphic-design/coarse-to-fine-rico25 |
not-published |
| PubLayNet | creative-graphic-design/coarse-to-fine-publaynet |
not-published |
Uses¶
Direct Use¶
Use this package for research inference, conversion checks, and agreement checks against the original implementation for generated layouts.
The released checkpoints support unconditional hierarchical generation only. Canonical condition_type names are normalized at the API boundary, and unsupported modes fail explicitly.
condition_type |
Required inputs | Support |
|---|---|---|
unconditional |
none | supported |
label, label_size, completion, refinement, text, content_image, relation, hierarchical, retrieval |
not applicable | raises NotImplementedError |
Downstream Use¶
Generated layouts may feed rendering, design tooling, layout evaluation, or downstream content placement systems after task-specific validation.
Out-of-Scope Use¶
Do not treat generated layouts as production accessibility annotations, OCR output, semantic scene understanding, or license-cleared design assets without separate review.
Bias, Risks, and Limitations¶
The converted behavior follows the upstream checkpoints, prompt fixtures, and datasets. Dataset coverage, label vocabularies, and layout quality inherit the limits of those sources.
Recommendations¶
Re-run the agreement-check suite against the original implementation before publishing converted checkpoints or comparing new results.
How to Get Started with the Model¶
Install the package directly from this repository. The command includes shared packages when they are not published on PyPI.
pip install \
"laygen @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=lib/laygen" \
"coarse-to-fine @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=models/coarse-to-fine"
Clone this repository, install the workspace member, and run the download and conversion steps in REPRODUCING.md. Those steps create .cache/coarse-to-fine/converted/rico25.
git clone https://github.com/creative-graphic-design/design-generators.git
cd design-generators
uv sync --package coarse-to-fine
uv run --package coarse-to-fine python
from coarse_to_fine import (
CoarseToFineForLayoutGeneration,
CoarseToFinePipeline,
CoarseToFineProcessor,
)
path = ".cache/coarse-to-fine/converted/rico25"
# After Hub publication: from_pretrained("creative-graphic-design/coarse-to-fine-rico25")
model = CoarseToFineForLayoutGeneration.from_pretrained(path)
processor = CoarseToFineProcessor.from_pretrained(path)
pipe = CoarseToFinePipeline(model=model, processor=processor)
out = pipe(batch_size=2, seed=0, return_intermediates=True)
print(out.bbox.shape)
print(out.labels.shape)
print(out.id2label[int(out.labels[out.mask][0])])
print(out.intermediates["hierarchy"]["group_bbox"].shape)
Training Details¶
Training Data¶
| Dataset | Dataset ID | Notes |
|---|---|---|
| RICO25 | creative-graphic-design/Rico |
ui-screenshots-and-hierarchies-with-semantic-annotations |
| PubLayNet | creative-graphic-design/PubLayNet |
default |
RICO25 public labels are zero-based; original-implementation tensors use one-based labels with SOS/EOS ids. PubLayNet COCO-style document boxes are converted to normalized ltwh, discretized on the original 128-bin grid, and returned publicly as normalized center xywh.
Training Procedure¶
This package ports released behavior and does not retrain the method in this repository.
Preprocessing¶
Inputs and outputs are normalized to the public layout schema at package boundaries. Boxes, tokens, prompts, or analog bits that follow the original implementation stay inside package adapters and fixtures used for agreement checks.
Training Hyperparameters¶
- Training regime: original upstream training; not rerun in this repository.
Speeds, Sizes, Times¶
Training-time and carbon measurements are unknown.
Evaluation¶
Testing Data, Factors & Metrics¶
Testing Data¶
Agreement checks use local-only generated fixtures and converted checkpoint directories. Large generated tensors, images, weights, and downloaded artifacts are not committed.
Factors¶
Agreement results are reported separately by dataset, checkpoint, condition mode, seed, or prompt fixture where the package has recorded evidence.
Metrics¶
Metrics are exact tensor equality, exact token or byte equality, or an explicitly stated numeric tolerance against the original implementation.
Parity Results¶
| Dataset | Comparison target | Cases | Agreement criterion | Result |
|---|---|---|---|---|
| RICO25 | Strict checkpoint conversion + from_pretrained |
1 checkpoint | Missing/unexpected keys fail strict load | Pass |
| RICO25 | Original implementation vs converted hierarchy logits | batch 2, 20 groups/elements | rtol=5e-5, atol=5e-5; greedy argmax exact |
Pass; max abs 3.004e-05 |
| PubLayNet | Strict checkpoint conversion + from_pretrained |
1 checkpoint | Missing/unexpected keys fail strict load | Pass |
| PubLayNet | Original implementation vs converted hierarchy logits | batch 2, 20 groups/elements | rtol=5e-5, atol=5e-5; greedy argmax exact |
Pass; max abs 7.75e-06 |
Detailed max-abs values for the logits checks were:
| Dataset | Group bbox | Group label histogram | Grouped bbox | Grouped label | Argmax |
|---|---|---|---|---|---|
| RICO25 | 3.004e-05 |
2.026e-06 |
2.098e-05 |
2.193e-05 |
exact |
| PubLayNet | 3.814e-06 |
5.960e-07 |
5.600e-06 |
7.750e-06 |
exact |
Reproducibility¶
See REPRODUCING.md for the commands that download original-implementation assets, generate reference outputs, run agreement checks, convert checkpoints, and smoke-test local loading.
Environmental Impact¶
No new model training is performed by these conversion packages. Conversion and parity costs depend on the selected checkpoint and local hardware.
Technical Specifications¶
Model Architecture and Objective¶
Coarse-to-Fine uses an autoregressive Transformer decoder with separate heads for element labels, group label histograms, and four coordinate bins. Generated hierarchy data is returned through intermediates when requested. There is no single unified token vocabulary for layout serialization, so Coarse-to-Fine uses a ProcessorMixin processor instead of a PreTrainedTokenizer.
Compute Infrastructure¶
Agreement-check commands are intended for one explicitly selected GPU when the original implementation requires CUDA.
Hardware¶
CPU is sufficient for import and most smoke tests. CUDA is required for heavyweight agreement checks when the original implementation requires it.
Software¶
Use uv run --package coarse-to-fine ... from the repository root so workspace dependency sources and extras resolve correctly.
License¶
Repository wrapper code is Apache-2.0. The original Microsoft LayoutGeneration repository is MIT licensed. Converted code in this package is for research conversion and evaluation of the released Coarse-to-Fine checkpoints.
Citation¶
@inproceedings{jiang2022coarse,
title = {Coarse-to-Fine Generative Modeling for Graphic Layouts},
author = {Jiang, Zhaoyun and Sun, Shizhao and Zhu, Jihua and Lou, Jian-Guang and Zhang, Dongmei},
booktitle = {AAAI},
year = {2022}
}
API Reference¶
Transformers-style Coarse-to-Fine layout generation components.
CoarseToFineConfig ¶
Bases: PretrainedConfig
Stores architecture, discretization, and label metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
DatasetName | str
|
Dataset name for the converted checkpoint. |
rico25
|
num_labels
|
int | None
|
Optional label vocabulary size. Defaults to the dataset vocabulary length. |
None
|
id2label
|
Mapping[int | str, str] | None
|
Optional label id to display-label mapping. |
None
|
label2id
|
Mapping[str, int] | None
|
Optional display-label to id mapping. |
None
|
max_num_elements
|
int
|
Maximum flat element count used by the checkpoint model. |
20
|
discrete_x_grid
|
int
|
Number of x-axis bins. |
128
|
discrete_y_grid
|
int
|
Number of y-axis bins. |
128
|
d_model
|
int
|
Transformer hidden dimension. |
512
|
d_z
|
int
|
VAE latent dimension. |
512
|
n_layers
|
int
|
Number of encoder layers. |
4
|
n_layers_decoder
|
int
|
Number of decoder layers. |
4
|
n_heads
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Transformer feed-forward dimension. |
2048
|
dropout
|
float
|
Dropout probability. |
0.1
|
internal_box_format
|
BoxFormat | str
|
Reference internal box format. |
ltwh
|
public_box_format
|
BoxFormat | str
|
Public output box format. |
xywh
|
vendor_label_offset
|
int
|
Offset from public label ids to internal ids. |
1
|
**kwargs
|
str | int | float | bool | None
|
Additional |
{}
|
Examples:
>>> CoarseToFineConfig(dataset="publaynet").num_labels
5
Source code in models/coarse-to-fine/src/coarse_to_fine/configuration_coarse_to_fine.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
__init__ ¶
__init__(
dataset: DatasetName | str = DatasetName.rico25,
num_labels: int | None = None,
id2label: Mapping[int | str, str] | None = None,
label2id: Mapping[str, int] | None = None,
max_num_elements: int = 20,
discrete_x_grid: int = 128,
discrete_y_grid: int = 128,
d_model: int = 512,
d_z: int = 512,
n_layers: int = 4,
n_layers_decoder: int = 4,
n_heads: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.1,
internal_box_format: BoxFormat | str = BoxFormat.ltwh,
public_box_format: BoxFormat | str = BoxFormat.xywh,
vendor_label_offset: int = 1,
eval_batch_size: int | None = None,
**kwargs: str | int | float | bool | None,
) -> None
Initialize Coarse-to-Fine config values.
Source code in models/coarse-to-fine/src/coarse_to_fine/configuration_coarse_to_fine.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
CoarseToFineHierarchy
dataclass
¶
Decoded Coarse-to-Fine hierarchy returned in intermediates.
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
27 28 29 30 31 32 33 34 35 36 37 38 | |
CoarseToFineHierarchyEncoding
dataclass
¶
Training/reference hierarchy tensors before padding.
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
41 42 43 44 45 46 47 48 | |
CoarseToFineForLayoutGeneration ¶
Bases: PreTrainedModel
Transformers PreTrainedModel with checkpoint-compatible module names.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | |
__init__ ¶
__init__(config: CoarseToFineConfig) -> None
Initialize checkpoint-compatible modules.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
496 497 498 499 500 501 502 503 504 | |
forward ¶
forward(
labels: Int[Tensor, "batch elements"],
bbox: Int[Tensor, "batch elements 4"],
mask: Bool[Tensor, "batch elements"],
group_bounding_box: Int[Tensor, "batch seq 4"],
label_in_one_group: Float[Tensor, "batch seq vocab"],
group_mask: Bool[Tensor, "batch seq"],
grouped_bbox: Int[Tensor, "batch seq elements 4"],
grouped_labels: Int[Tensor, "batch seq elements"],
grouped_mask: Bool[Tensor, "batch seq elements"],
latent_z: Float[Tensor, "1 batch latent"] | None = None,
use_teacher_forcing: bool = True,
return_dict: bool | None = None,
) -> (
dict[str, Shaped[torch.Tensor, "..."]]
| tuple[Shaped[torch.Tensor, "..."], ...]
)
Run teacher-forced or greedy hierarchical decoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Int[Tensor, 'batch elements']
|
Batch-first internal label ids. |
required |
bbox
|
Int[Tensor, 'batch elements 4']
|
Batch-first discrete |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Batch-first valid element mask. |
required |
group_bounding_box
|
Int[Tensor, 'batch seq 4']
|
Batch-first group discrete |
required |
label_in_one_group
|
Float[Tensor, 'batch seq vocab']
|
Batch-first group label histograms. |
required |
group_mask
|
Bool[Tensor, 'batch seq']
|
Batch-first valid group mask. |
required |
grouped_bbox
|
Int[Tensor, 'batch seq elements 4']
|
Batch-first group-relative discrete |
required |
grouped_labels
|
Int[Tensor, 'batch seq elements']
|
Batch-first group-relative internal labels. |
required |
grouped_mask
|
Bool[Tensor, 'batch seq elements']
|
Batch-first valid grouped-element mask. |
required |
latent_z
|
Float[Tensor, '1 batch latent'] | None
|
Optional latent tensor to bypass stochastic sampling. |
None
|
use_teacher_forcing
|
bool
|
Whether to use provided hierarchy tensors. |
True
|
return_dict
|
bool | None
|
Return a dictionary when true. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']] | tuple[Shaped[Tensor, '...'], ...]
|
Dictionary of raw logits and latent tensors. |
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | |
CoarseToFinePipeline ¶
Bases: Pipeline
Orchestrate Coarse-to-Fine layout generation.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
__init__ ¶
__init__(
model: CoarseToFineForLayoutGeneration,
processor: CoarseToFineProcessor,
) -> None
Initialize the pipeline with a model and processor.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
49 50 51 52 53 54 55 56 | |
preprocess ¶
preprocess(
input_: CoarseToFinePipelineParameter,
**preprocess_parameters: dict[
str, CoarseToFinePipelineParameter
],
) -> dict[str, GenericTensor]
Satisfy the abstract pipeline API; direct calls bypass this path.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
67 68 69 70 71 72 73 74 | |
postprocess ¶
postprocess(
model_outputs: LayoutGenerationOutput
| CoarseToFineOutputDict,
**kwargs: dict[str, CoarseToFinePipelineParameter],
) -> LayoutGenerationOutput | CoarseToFineOutputDict
Return model outputs without additional formatting.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
84 85 86 87 88 89 90 91 | |
__call__ ¶
__call__(
*,
batch_size: int = 1,
seed: int | None = None,
generator: Generator | None = None,
condition_type: ConditionType
| str = ConditionType.unconditional,
labels: Int[Tensor, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
bbox: Float[Tensor, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
num_inference_steps: int | None = None,
output_type: OutputType | str = OutputType.dataclass,
return_intermediates: bool = False,
latent_z: Float[Tensor, "1 batch latent"] | None = None,
) -> LayoutGenerationOutput | CoarseToFineOutputDict
Generate layouts through model decode and processor post-processing.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
CoarseToFineProcessor ¶
Bases: ProcessorMixin
Convert public layouts to Coarse-to-Fine hierarchy tensors.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
__init__ ¶
__init__(
dataset: DatasetName | str = DatasetName.rico25,
*,
x_grid: int = 128,
y_grid: int = 128,
max_num_elements: int = 20,
id2label: dict[int, str] | None = None,
) -> None
Initialize label maps and discretization settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
DatasetName | str
|
Canonical layout dataset. |
rico25
|
x_grid
|
int
|
Number of x/width bins. |
128
|
y_grid
|
int
|
Number of y/height bins. |
128
|
max_num_elements
|
int
|
Padded flat sequence length. |
20
|
id2label
|
dict[int, str] | None
|
Optional public label map. |
None
|
Examples:
>>> CoarseToFineProcessor(dataset="publaynet").id2label[0]
'text'
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
from_config
classmethod
¶
from_config(
dataset: DatasetName | str = DatasetName.rico25,
*,
x_grid: int = 128,
y_grid: int = 128,
max_num_elements: int = 20,
id2label: dict[int, str] | None = None,
) -> "CoarseToFineProcessor"
Construct a processor without external files.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
to_dict ¶
to_dict() -> dict[str, str | int | dict[str, str]]
Serialize processor state to a JSON-compatible dictionary.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
81 82 83 84 85 86 87 88 89 90 | |
save_pretrained ¶
save_pretrained(
save_directory: str | PathLike[str],
push_to_hub: bool = False,
**kwargs: str | int | float | bool | None,
) -> list[str]
Save processor metadata next to a converted checkpoint.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
92 93 94 95 96 97 98 99 100 101 102 103 104 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | PathLike[str],
cache_dir: str | PathLike[str] | None = None,
force_download: bool = False,
local_files_only: bool = False,
token: str | bool | None = None,
revision: str = "main",
**kwargs: str | int | float | bool | None,
) -> "CoarseToFineProcessor"
Load processor metadata from a local save_pretrained directory.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
__call__ ¶
__call__(
labels: list[list[int | str]]
| Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| None = None,
bbox: list[list[list[float]]]
| Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
return_tensors: Literal["pt"] = "pt",
) -> BatchEncoding
Build discrete flat tensors from public layout inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
list[list[int | str]] | Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | None
|
Public zero-based labels or label strings. |
None
|
bbox
|
list[list[list[float]]] | Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | None
|
Public normalized boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | None
|
Optional valid-element mask. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Must be true; pixel boxes are dataset-loader work. |
True
|
return_tensors
|
Literal['pt']
|
Only |
'pt'
|
Returns:
| Type | Description |
|---|---|
BatchEncoding
|
BatchEncoding with internal labels, discrete boxes, and masks. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If labels or boxes are missing. |
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
build_hierarchy_batch ¶
build_hierarchy_batch(
labels: Int[Tensor, "batch elements"],
bbox: Float[Tensor, "batch elements 4"],
mask: Bool[Tensor, "batch elements"],
) -> BatchEncoding
Build padded hierarchy tensors for training/reference batches.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
post_process_hierarchy ¶
post_process_hierarchy(
hierarchy: CoarseToFineHierarchy,
output_type: OutputType | str = OutputType.dataclass,
return_intermediates: bool = False,
) -> (
LayoutGenerationOutput
| dict[
str,
Float[torch.Tensor, "..."]
| Int[torch.Tensor, "..."]
| Bool[torch.Tensor, "..."]
| dict[int, str]
| None,
]
)
Convert decoded hierarchy tensors to the shared output schema.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
OutputType ¶
Bases: StrEnum
Supported output containers.
Source code in models/coarse-to-fine/src/coarse_to_fine/types.py
10 11 12 13 14 | |
configuration_coarse_to_fine ¶
Configuration for Coarse-to-Fine checkpoints.
CoarseToFineConfig ¶
Bases: PretrainedConfig
Stores architecture, discretization, and label metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
DatasetName | str
|
Dataset name for the converted checkpoint. |
rico25
|
num_labels
|
int | None
|
Optional label vocabulary size. Defaults to the dataset vocabulary length. |
None
|
id2label
|
Mapping[int | str, str] | None
|
Optional label id to display-label mapping. |
None
|
label2id
|
Mapping[str, int] | None
|
Optional display-label to id mapping. |
None
|
max_num_elements
|
int
|
Maximum flat element count used by the checkpoint model. |
20
|
discrete_x_grid
|
int
|
Number of x-axis bins. |
128
|
discrete_y_grid
|
int
|
Number of y-axis bins. |
128
|
d_model
|
int
|
Transformer hidden dimension. |
512
|
d_z
|
int
|
VAE latent dimension. |
512
|
n_layers
|
int
|
Number of encoder layers. |
4
|
n_layers_decoder
|
int
|
Number of decoder layers. |
4
|
n_heads
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Transformer feed-forward dimension. |
2048
|
dropout
|
float
|
Dropout probability. |
0.1
|
internal_box_format
|
BoxFormat | str
|
Reference internal box format. |
ltwh
|
public_box_format
|
BoxFormat | str
|
Public output box format. |
xywh
|
vendor_label_offset
|
int
|
Offset from public label ids to internal ids. |
1
|
**kwargs
|
str | int | float | bool | None
|
Additional |
{}
|
Examples:
>>> CoarseToFineConfig(dataset="publaynet").num_labels
5
Source code in models/coarse-to-fine/src/coarse_to_fine/configuration_coarse_to_fine.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
__init__ ¶
__init__(
dataset: DatasetName | str = DatasetName.rico25,
num_labels: int | None = None,
id2label: Mapping[int | str, str] | None = None,
label2id: Mapping[str, int] | None = None,
max_num_elements: int = 20,
discrete_x_grid: int = 128,
discrete_y_grid: int = 128,
d_model: int = 512,
d_z: int = 512,
n_layers: int = 4,
n_layers_decoder: int = 4,
n_heads: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.1,
internal_box_format: BoxFormat | str = BoxFormat.ltwh,
public_box_format: BoxFormat | str = BoxFormat.xywh,
vendor_label_offset: int = 1,
eval_batch_size: int | None = None,
**kwargs: str | int | float | bool | None,
) -> None
Initialize Coarse-to-Fine config values.
Source code in models/coarse-to-fine/src/coarse_to_fine/configuration_coarse_to_fine.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
conversion ¶
Checkpoint conversion helpers for Coarse-to-Fine.
strip_module_prefix ¶
strip_module_prefix(
state_dict: dict[str, Shaped[Tensor, "..."]],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Remove optional DDP module. prefixes from checkpoint keys.
Source code in models/coarse-to-fine/src/coarse_to_fine/conversion.py
17 18 19 20 21 | |
convert_checkpoint ¶
convert_checkpoint(
checkpoint: str | Path,
*,
dataset: DatasetName | str,
output_dir: str | Path,
) -> CoarseToFineForLayoutGeneration
Convert a raw vendor state dict into save_pretrained format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint
|
str | Path
|
Path to |
required |
dataset
|
DatasetName | str
|
Dataset for config defaults. |
required |
output_dir
|
str | Path
|
Destination directory. |
required |
Returns:
| Type | Description |
|---|---|
CoarseToFineForLayoutGeneration
|
The loaded model. |
Source code in models/coarse-to-fine/src/coarse_to_fine/conversion.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
geometry ¶
Geometry helpers for Coarse-to-Fine discretization and hierarchy math.
public_to_ltwh ¶
public_to_ltwh(
bbox: Float[Tensor, "... 4"],
*,
box_format: BoxFormat | str = BoxFormat.xywh,
) -> Float[torch.Tensor, "... 4"]
Convert normalized public boxes to normalized left-top ltwh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, '... 4']
|
Box tensor with the selected input format. |
required |
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, '... 4']
|
Normalized |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the box format is unsupported. |
Examples:
>>> import torch
>>> public_to_ltwh(torch.tensor([[[0.5, 0.5, 0.2, 0.2]]])).shape
torch.Size([1, 1, 4])
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
ltwh_to_public_xywh ¶
ltwh_to_public_xywh(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert normalized ltwh boxes to public normalized center xywh.
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
54 55 56 57 58 | |
discretize_ltwh ¶
discretize_ltwh(
bbox: Float[Tensor, "... 4"],
*,
num_x_grid: int,
num_y_grid: int,
) -> Int[torch.Tensor, "... 4"]
Discretize normalized ltwh with the reference floor(coord*(grid-1)) rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, '... 4']
|
Normalized |
required |
num_x_grid
|
int
|
Number of x/width bins. |
required |
num_y_grid
|
int
|
Number of y/height bins. |
required |
Returns:
| Type | Description |
|---|---|
Int[Tensor, '... 4']
|
Integer |
Examples:
>>> import torch
>>> discretize_ltwh(torch.tensor([[1.0, 0.5, 0.0, 0.5]]), num_x_grid=128, num_y_grid=128)
tensor([[127, 63, 0, 63]])
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
continuize_ltwh ¶
continuize_ltwh(
ids: Int[Tensor, "... 4"],
*,
num_x_grid: int,
num_y_grid: int,
) -> Float[torch.Tensor, "... 4"]
Convert discrete ltwh ids back to normalized coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids
|
Int[Tensor, '... 4']
|
Integer |
required |
num_x_grid
|
int
|
Number of x/width bins. |
required |
num_y_grid
|
int
|
Number of y/height bins. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, '... 4']
|
Normalized |
Examples:
>>> import torch
>>> continuize_ltwh(torch.tensor([[127, 63, 0, 63]]), num_x_grid=128, num_y_grid=128).shape
torch.Size([1, 4])
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
relative_ltwh_to_absolute_ltwh ¶
relative_ltwh_to_absolute_ltwh(
relative_bbox: Float[Tensor, "... 4"],
group_bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert group-relative ltwh boxes to absolute normalized ltwh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_bbox
|
Float[Tensor, '... 4']
|
Relative left, top, width, height inside the group. |
required |
group_bbox
|
Float[Tensor, '... 4']
|
Absolute group |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, '... 4']
|
Absolute normalized |
Examples:
>>> import torch
>>> relative_ltwh_to_absolute_ltwh(
... torch.tensor([[0.5, 0.0, 0.5, 1.0]]),
... torch.tensor([[0.0, 0.0, 0.4, 0.2]]),
... )
tensor([[0.2000, 0.0000, 0.2000, 0.2000]])
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
ltwh_to_ltrb ¶
ltwh_to_ltrb(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert ltwh boxes to ltrb boxes.
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
151 152 153 154 | |
ltrb_to_ltwh ¶
ltrb_to_ltwh(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert ltrb boxes to ltwh boxes.
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
157 158 159 160 | |
public_to_ltrb ¶
public_to_ltrb(
bbox: Float[Tensor, "... 4"],
*,
box_format: BoxFormat | str = BoxFormat.xywh,
) -> Float[torch.Tensor, "... 4"]
Convert normalized public boxes to normalized ltrb.
Source code in models/coarse-to-fine/src/coarse_to_fine/geometry.py
163 164 165 166 167 168 169 170 171 172 173 174 | |
hierarchy ¶
Hierarchy carriers and CutHierarchy-compatible processing.
CoarseToFineHierarchy
dataclass
¶
Decoded Coarse-to-Fine hierarchy returned in intermediates.
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
27 28 29 30 31 32 33 34 35 36 37 38 | |
CoarseToFineHierarchyEncoding
dataclass
¶
Training/reference hierarchy tensors before padding.
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
41 42 43 44 45 46 47 48 | |
build_cut_hierarchy ¶
build_cut_hierarchy(
bbox_ltwh: Float[Tensor, "elements 4"],
labels_1based: Int[Tensor, "elements"],
*,
num_labels: int,
discrete_x_grid: int,
discrete_y_grid: int,
) -> CoarseToFineHierarchyEncoding
Build the checkpoint bottom-two hierarchy for one layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox_ltwh
|
Float[Tensor, 'elements 4']
|
Normalized |
required |
labels_1based
|
Int[Tensor, 'elements']
|
Internal one-based labels for valid elements. |
required |
num_labels
|
int
|
Number of dataset labels. |
required |
discrete_x_grid
|
int
|
Number of x bins. |
required |
discrete_y_grid
|
int
|
Number of y bins. |
required |
Returns:
| Type | Description |
|---|---|
CoarseToFineHierarchyEncoding
|
Unpadded hierarchy encoding with discrete group and relative boxes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the layout has no valid elements. |
Examples:
>>> import torch
>>> enc = build_cut_hierarchy(
... torch.tensor([[0.0, 0.0, 0.2, 0.2], [0.5, 0.0, 0.2, 0.2]]),
... torch.tensor([1, 2]),
... num_labels=2,
... discrete_x_grid=128,
... discrete_y_grid=128,
... )
>>> enc.group_bounding_box.shape[-1]
4
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
flatten_hierarchy ¶
flatten_hierarchy(
hierarchy: CoarseToFineHierarchy,
*,
id2label: dict[int, str],
max_num_elements: int | None = None,
) -> LayoutGenerationOutput
Flatten a decoded hierarchy to the shared output schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hierarchy
|
CoarseToFineHierarchy
|
Decoded Coarse-to-Fine hierarchy. |
required |
id2label
|
dict[int, str]
|
Public label mapping. |
required |
max_num_elements
|
int | None
|
Optional output padding length. |
None
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput
|
Shared layout output with hierarchy metadata in |
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
decode_hierarchy_from_logits ¶
decode_hierarchy_from_logits(
*,
group_bbox_logits: Float[
Tensor, "batch group_tokens 4 bbox_vocab"
],
group_label_logits: Float[
Tensor, "batch group_tokens group_label_vocab"
],
grouped_bbox_logits: Float[
Tensor, "batch groups elements 4 bbox_vocab"
],
grouped_label_logits: Float[
Tensor, "batch groups elements element_label_vocab"
],
num_labels: int,
group_eos_index: int,
element_eos_id: int,
discrete_x_grid: int,
discrete_y_grid: int,
) -> CoarseToFineHierarchy
Decode argmax group/element logits into hierarchy tensors.
Source code in models/coarse-to-fine/src/coarse_to_fine/hierarchy.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
modeling_coarse_to_fine ¶
PyTorch model wrapper for Coarse-to-Fine layout generation.
LayoutEmbedding ¶
Bases: Module
Checkpoint-compatible label, box, and group-label embeddings.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
__init__ ¶
__init__(config: CoarseToFineConfig) -> None
Initialize embedding tables.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
86 87 88 89 90 91 92 93 94 | |
get_label_embedding ¶
get_label_embedding(
label: Int[Tensor, "..."],
) -> Float[torch.Tensor, "... channels"]
Embed element labels.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
101 102 103 104 105 | |
get_box_embedding ¶
get_box_embedding(
box: Int[Tensor, "seq batch 4"],
) -> Float[torch.Tensor, "seq batch box_channels"]
Embed four discrete box-coordinate ids and concatenate them.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
107 108 109 110 111 112 113 | |
get_group_label_embedding ¶
get_group_label_embedding(
label: Float[Tensor, "seq batch group_label_vocab"],
) -> Float[torch.Tensor, "seq batch channels"]
Embed per-group label histograms.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
115 116 117 118 119 | |
forward ¶
forward(
label: Int[Tensor, "seq batch"],
box: Int[Tensor, "seq batch 4"],
) -> Float[torch.Tensor, "seq batch channels"]
Embed labels and boxes into transformer hidden states.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
121 122 123 124 125 126 127 128 129 | |
Encoder ¶
Bases: Module
Checkpoint-compatible layout encoder.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
__init__ ¶
__init__(
config: CoarseToFineConfig, layout_embd: LayoutEmbedding
) -> None
Initialize the transformer encoder.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
forward ¶
forward(
labels: Int[Tensor, "seq batch"],
bboxes: Int[Tensor, "seq batch 4"],
masks: Bool[Tensor, "batch seq"],
) -> Float[torch.Tensor, "1 batch channels"]
Encode a seq-first padded layout and mean-pool valid states.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
VAE ¶
Bases: Module
Checkpoint-compatible latent sampler.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
__init__ ¶
__init__(config: CoarseToFineConfig) -> None
Initialize latent projections.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
172 173 174 175 176 177 178 179 | |
forward ¶
forward(
memory: Float[Tensor, "1 batch channels"],
) -> tuple[
Float[torch.Tensor, "1 batch latent"],
Float[torch.Tensor, "1 batch latent"],
Float[torch.Tensor, "1 batch latent"],
]
Sample latent z from encoded memory.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
187 188 189 190 191 192 193 194 195 196 197 198 199 | |
inference ¶
inference(
z: Float[Tensor, "1 batch latent"] | None,
*,
batch_size: int,
device: device,
) -> Float[torch.Tensor, "1 batch latent"]
Return seq-first latent tensor for generation.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
GroupDecoder ¶
Bases: Module
Autoregressive group box and label-histogram decoder.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
__init__ ¶
__init__(
config: CoarseToFineConfig, layout_embd: LayoutEmbedding
) -> None
Initialize group decoder modules.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
forward ¶
forward(
label: Float[Tensor, "seq batch group_label_vocab"],
box: Int[Tensor, "seq batch 4"],
z: Float[Tensor, "1 batch channels"],
mask: Bool[Tensor, "batch seq"],
) -> tuple[
Float[torch.Tensor, "seq_minus_eos batch channels"],
Float[torch.Tensor, "seq batch box_logits"],
Float[torch.Tensor, "seq batch group_label_vocab"],
]
Teacher-forced group decoding.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
inference ¶
inference(
z: Float[Tensor, "1 batch channels"],
*,
max_group_num: int,
device: device,
) -> tuple[
Float[torch.Tensor, "seq_minus_eos batch channels"],
Float[torch.Tensor, "seq batch box_logits"],
Float[torch.Tensor, "seq batch group_label_vocab"],
]
Greedy autoregressive group decoding.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
ElementDecoder ¶
Bases: Module
Autoregressive element decoder conditioned on group memory.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |
__init__ ¶
__init__(
config: CoarseToFineConfig, layout_embd: LayoutEmbedding
) -> None
Initialize element decoder modules.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
forward ¶
forward(
label: Int[Tensor, "seq groups batch 1"],
box: Int[Tensor, "seq groups batch 4"],
memory: Float[Tensor, "groups batch channels"],
z: Float[Tensor, "1 batch channels"],
mask: Bool[Tensor, "batch groups seq"],
) -> tuple[
Float[torch.Tensor, "seq groups batch box_logits"],
Float[torch.Tensor, "seq groups batch label_logits"],
]
Teacher-forced element decoding.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | |
inference ¶
inference(
memory: Float[Tensor, "groups batch channels"],
z: Float[Tensor, "1 batch channels"],
*,
max_num_elements: int,
device: device,
) -> tuple[
Float[torch.Tensor, "seq groups batch box_logits"],
Float[torch.Tensor, "seq groups batch label_logits"],
]
Greedy autoregressive element decoding.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |
CoarseToFineForLayoutGeneration ¶
Bases: PreTrainedModel
Transformers PreTrainedModel with checkpoint-compatible module names.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | |
__init__ ¶
__init__(config: CoarseToFineConfig) -> None
Initialize checkpoint-compatible modules.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
496 497 498 499 500 501 502 503 504 | |
forward ¶
forward(
labels: Int[Tensor, "batch elements"],
bbox: Int[Tensor, "batch elements 4"],
mask: Bool[Tensor, "batch elements"],
group_bounding_box: Int[Tensor, "batch seq 4"],
label_in_one_group: Float[Tensor, "batch seq vocab"],
group_mask: Bool[Tensor, "batch seq"],
grouped_bbox: Int[Tensor, "batch seq elements 4"],
grouped_labels: Int[Tensor, "batch seq elements"],
grouped_mask: Bool[Tensor, "batch seq elements"],
latent_z: Float[Tensor, "1 batch latent"] | None = None,
use_teacher_forcing: bool = True,
return_dict: bool | None = None,
) -> (
dict[str, Shaped[torch.Tensor, "..."]]
| tuple[Shaped[torch.Tensor, "..."], ...]
)
Run teacher-forced or greedy hierarchical decoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Int[Tensor, 'batch elements']
|
Batch-first internal label ids. |
required |
bbox
|
Int[Tensor, 'batch elements 4']
|
Batch-first discrete |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Batch-first valid element mask. |
required |
group_bounding_box
|
Int[Tensor, 'batch seq 4']
|
Batch-first group discrete |
required |
label_in_one_group
|
Float[Tensor, 'batch seq vocab']
|
Batch-first group label histograms. |
required |
group_mask
|
Bool[Tensor, 'batch seq']
|
Batch-first valid group mask. |
required |
grouped_bbox
|
Int[Tensor, 'batch seq elements 4']
|
Batch-first group-relative discrete |
required |
grouped_labels
|
Int[Tensor, 'batch seq elements']
|
Batch-first group-relative internal labels. |
required |
grouped_mask
|
Bool[Tensor, 'batch seq elements']
|
Batch-first valid grouped-element mask. |
required |
latent_z
|
Float[Tensor, '1 batch latent'] | None
|
Optional latent tensor to bypass stochastic sampling. |
None
|
use_teacher_forcing
|
bool
|
Whether to use provided hierarchy tensors. |
True
|
return_dict
|
bool | None
|
Return a dictionary when true. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']] | tuple[Shaped[Tensor, '...'], ...]
|
Dictionary of raw logits and latent tensors. |
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | |
make_seq_first ¶
make_seq_first(
arg: Shaped[Tensor, "batch seq ..."],
) -> Shaped[torch.Tensor, "seq batch ..."]
Convert (batch, seq, ...) tensors to (seq, batch, ...).
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
17 18 19 20 21 22 | |
make_batch_first ¶
make_batch_first(
arg: Shaped[Tensor, "seq batch ..."],
) -> Shaped[torch.Tensor, "batch seq ..."]
Convert (seq, batch, ...) tensors to (batch, seq, ...).
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
25 26 27 28 29 30 | |
get_key_padding_mask ¶
get_key_padding_mask(
mask: Bool[Tensor, "batch seq"],
) -> Bool[torch.Tensor, "batch seq"]
Match the checkpoint cumulative padding-mask convention.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
33 34 35 36 37 | |
get_padding_mask ¶
get_padding_mask(
mask: Bool[Tensor, "batch seq"],
) -> Bool[torch.Tensor, "seq batch 1"]
Convert batch-first mask to seq-first broadcast mask.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
40 41 42 43 44 | |
make_group_first ¶
make_group_first(
arg: Shaped[Tensor, "seq groups batch ..."],
) -> Shaped[torch.Tensor, "groups seq batch ..."]
Convert (seq, group, batch, ...) to (group, seq, batch, ...).
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
47 48 49 50 51 | |
pack_group_batch ¶
pack_group_batch(
*args: Shaped[Tensor, "seq groups batch ..."],
) -> tuple[
Shaped[torch.Tensor, "seq group_batch ..."], ...
]
Flatten group and batch dimensions in seq-first grouped tensors.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
54 55 56 57 58 59 60 61 | |
unpack_group_batch ¶
unpack_group_batch(
batch_size: int,
*args: Shaped[Tensor, "seq group_batch ..."],
) -> tuple[
Shaped[torch.Tensor, "seq groups batch ..."], ...
]
Restore (seq, group, batch, ...) tensors from packed group batches.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
64 65 66 67 68 69 70 | |
generate_square_subsequent_mask ¶
generate_square_subsequent_mask(
size: int, device: device
) -> Float[torch.Tensor, "size size"]
Create the causal decoder mask used by the checkpoint model.
Source code in models/coarse-to-fine/src/coarse_to_fine/modeling_coarse_to_fine.py
73 74 75 76 77 78 79 80 | |
pipeline_coarse_to_fine ¶
Pipeline wrapper for Coarse-to-Fine.
CoarseToFinePipeline ¶
Bases: Pipeline
Orchestrate Coarse-to-Fine layout generation.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
__init__ ¶
__init__(
model: CoarseToFineForLayoutGeneration,
processor: CoarseToFineProcessor,
) -> None
Initialize the pipeline with a model and processor.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
49 50 51 52 53 54 55 56 | |
preprocess ¶
preprocess(
input_: CoarseToFinePipelineParameter,
**preprocess_parameters: dict[
str, CoarseToFinePipelineParameter
],
) -> dict[str, GenericTensor]
Satisfy the abstract pipeline API; direct calls bypass this path.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
67 68 69 70 71 72 73 74 | |
postprocess ¶
postprocess(
model_outputs: LayoutGenerationOutput
| CoarseToFineOutputDict,
**kwargs: dict[str, CoarseToFinePipelineParameter],
) -> LayoutGenerationOutput | CoarseToFineOutputDict
Return model outputs without additional formatting.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
84 85 86 87 88 89 90 91 | |
__call__ ¶
__call__(
*,
batch_size: int = 1,
seed: int | None = None,
generator: Generator | None = None,
condition_type: ConditionType
| str = ConditionType.unconditional,
labels: Int[Tensor, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
bbox: Float[Tensor, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
num_inference_steps: int | None = None,
output_type: OutputType | str = OutputType.dataclass,
return_intermediates: bool = False,
latent_z: Float[Tensor, "1 batch latent"] | None = None,
) -> LayoutGenerationOutput | CoarseToFineOutputDict
Generate layouts through model decode and processor post-processing.
Source code in models/coarse-to-fine/src/coarse_to_fine/pipeline_coarse_to_fine.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
processing_coarse_to_fine ¶
Processor for Coarse-to-Fine layouts and hierarchy tensors.
CoarseToFineProcessor ¶
Bases: ProcessorMixin
Convert public layouts to Coarse-to-Fine hierarchy tensors.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
__init__ ¶
__init__(
dataset: DatasetName | str = DatasetName.rico25,
*,
x_grid: int = 128,
y_grid: int = 128,
max_num_elements: int = 20,
id2label: dict[int, str] | None = None,
) -> None
Initialize label maps and discretization settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
DatasetName | str
|
Canonical layout dataset. |
rico25
|
x_grid
|
int
|
Number of x/width bins. |
128
|
y_grid
|
int
|
Number of y/height bins. |
128
|
max_num_elements
|
int
|
Padded flat sequence length. |
20
|
id2label
|
dict[int, str] | None
|
Optional public label map. |
None
|
Examples:
>>> CoarseToFineProcessor(dataset="publaynet").id2label[0]
'text'
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
from_config
classmethod
¶
from_config(
dataset: DatasetName | str = DatasetName.rico25,
*,
x_grid: int = 128,
y_grid: int = 128,
max_num_elements: int = 20,
id2label: dict[int, str] | None = None,
) -> "CoarseToFineProcessor"
Construct a processor without external files.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
to_dict ¶
to_dict() -> dict[str, str | int | dict[str, str]]
Serialize processor state to a JSON-compatible dictionary.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
81 82 83 84 85 86 87 88 89 90 | |
save_pretrained ¶
save_pretrained(
save_directory: str | PathLike[str],
push_to_hub: bool = False,
**kwargs: str | int | float | bool | None,
) -> list[str]
Save processor metadata next to a converted checkpoint.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
92 93 94 95 96 97 98 99 100 101 102 103 104 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | PathLike[str],
cache_dir: str | PathLike[str] | None = None,
force_download: bool = False,
local_files_only: bool = False,
token: str | bool | None = None,
revision: str = "main",
**kwargs: str | int | float | bool | None,
) -> "CoarseToFineProcessor"
Load processor metadata from a local save_pretrained directory.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
__call__ ¶
__call__(
labels: list[list[int | str]]
| Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| None = None,
bbox: list[list[list[float]]]
| Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
return_tensors: Literal["pt"] = "pt",
) -> BatchEncoding
Build discrete flat tensors from public layout inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
list[list[int | str]] | Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | None
|
Public zero-based labels or label strings. |
None
|
bbox
|
list[list[list[float]]] | Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | None
|
Public normalized boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | None
|
Optional valid-element mask. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Must be true; pixel boxes are dataset-loader work. |
True
|
return_tensors
|
Literal['pt']
|
Only |
'pt'
|
Returns:
| Type | Description |
|---|---|
BatchEncoding
|
BatchEncoding with internal labels, discrete boxes, and masks. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If labels or boxes are missing. |
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
build_hierarchy_batch ¶
build_hierarchy_batch(
labels: Int[Tensor, "batch elements"],
bbox: Float[Tensor, "batch elements 4"],
mask: Bool[Tensor, "batch elements"],
) -> BatchEncoding
Build padded hierarchy tensors for training/reference batches.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
post_process_hierarchy ¶
post_process_hierarchy(
hierarchy: CoarseToFineHierarchy,
output_type: OutputType | str = OutputType.dataclass,
return_intermediates: bool = False,
) -> (
LayoutGenerationOutput
| dict[
str,
Float[torch.Tensor, "..."]
| Int[torch.Tensor, "..."]
| Bool[torch.Tensor, "..."]
| dict[int, str]
| None,
]
)
Convert decoded hierarchy tensors to the shared output schema.
Source code in models/coarse-to-fine/src/coarse_to_fine/processing_coarse_to_fine.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
types ¶
Closed public option sets for Coarse-to-Fine.
OutputType ¶
Bases: StrEnum
Supported output containers.
Source code in models/coarse-to-fine/src/coarse_to_fine/types.py
10 11 12 13 14 | |
normalize_output_type ¶
normalize_output_type(
output_type: OutputType | str,
) -> OutputType
Normalize a public output type value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_type
|
OutputType | str
|
Enum value or string. |
required |
Returns:
| Type | Description |
|---|---|
OutputType
|
Normalized output type. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the output type is unknown. |
Examples:
>>> str(normalize_output_type("dict"))
'dict'
Source code in models/coarse-to-fine/src/coarse_to_fine/types.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |