Skip to content

Ralf

RALF Transformers-style package.

RalfConfig

Bases: PretrainedConfig

Configuration carrying RALF architecture and tokenizer metadata.

Parameters:

Name Type Description Default
dataset_name RalfDatasetName

Poster dataset key, usually cgl or pku_posterlayout.

'cgl'
task RalfConfigTaskName

Canonical condition type or checkpoint task alias.

'unconditional'
id2label Mapping[int | str, str] | None

Dataset-local label vocabulary persisted with the checkpoint.

None
max_seq_length int

Maximum number of layout elements.

10
num_bin int

Number of linear geometry bins per variable.

128
var_order Sequence[RalfLayoutVariable]

Token variable order.

DEFAULT_VAR_ORDER
special_tokens Sequence[str]

Special tokens stored after label and geometry tokens.

DEFAULT_SPECIAL_TOKENS
geo_quantization str

Geometry quantizer name. The converted package supports linear; conversion records other values for audit.

'linear'
is_loc_vocab_shared bool

Whether geometry variables share one token range.

False
d_model int

Image encoder hidden size.

256
decoder_d_model int

Decoder hidden size.

256
encoder_layers int

Number of image encoder transformer layers.

6
decoder_layers int

Number of decoder layers.

6
num_attention_heads int

Number of attention heads.

8
dropout float

Dropout probability.

0.1
retrieval_backbone str

Retrieval backbone name.

'dreamsim'
top_k int

Number of retrieved examples expected by the checkpoint.

16
use_reference_image bool

Whether retrieved reference images participate in fusion.

False
layout_backbone str

Layout encoder name.

'feature_extractor'
freeze_layout_encoder bool

Whether the layout encoder was frozen.

True
fusion str

Retrieval fusion variant.

'concat_cross_attention'
use_flag_embedding bool

Whether task flag embeddings are enabled.

True
use_multitask bool

Whether checkpoint was trained as multitask.

False
global_task_embedding bool

Whether global task embedding is enabled.

False
relation_size int

Maximum number of relation constraints.

10
image_channels int

Number of image channels consumed by the model.

4
image_size tuple[int, int] | list[int] | None

Optional (height, width) resize target.

None
sort_order Sequence[str]

Processor sort order metadata.

('label', 'lexicographic')
retrieval_metadata RalfConfigMetadata | None

Retrieval-cache metadata for conversion/parity.

None
original_config RalfConfigMetadata | None

Original config serialized as plain data.

None
kwargs str | int | float | bool | None

Extra PretrainedConfig keyword arguments.

{}
Source code in models/ralf/src/ralf/configuration_ralf.py
 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
class RalfConfig(PretrainedConfig):
    """Configuration carrying RALF architecture and tokenizer metadata.

    Args:
        dataset_name: Poster dataset key, usually `cgl` or `pku_posterlayout`.
        task: Canonical condition type or checkpoint task alias.
        id2label: Dataset-local label vocabulary persisted with the checkpoint.
        max_seq_length: Maximum number of layout elements.
        num_bin: Number of linear geometry bins per variable.
        var_order: Token variable order.
        special_tokens: Special tokens stored after label and geometry tokens.
        geo_quantization: Geometry quantizer name. The converted package supports
            `linear`; conversion records other values for audit.
        is_loc_vocab_shared: Whether geometry variables share one token range.
        d_model: Image encoder hidden size.
        decoder_d_model: Decoder hidden size.
        encoder_layers: Number of image encoder transformer layers.
        decoder_layers: Number of decoder layers.
        num_attention_heads: Number of attention heads.
        dropout: Dropout probability.
        retrieval_backbone: Retrieval backbone name.
        top_k: Number of retrieved examples expected by the checkpoint.
        use_reference_image: Whether retrieved reference images participate in fusion.
        layout_backbone: Layout encoder name.
        freeze_layout_encoder: Whether the layout encoder was frozen.
        fusion: Retrieval fusion variant.
        use_flag_embedding: Whether task flag embeddings are enabled.
        use_multitask: Whether checkpoint was trained as multitask.
        global_task_embedding: Whether global task embedding is enabled.
        relation_size: Maximum number of relation constraints.
        image_channels: Number of image channels consumed by the model.
        image_size: Optional `(height, width)` resize target.
        sort_order: Processor sort order metadata.
        retrieval_metadata: Retrieval-cache metadata for conversion/parity.
        original_config: Original config serialized as plain data.
        kwargs: Extra `PretrainedConfig` keyword arguments.
    """

    model_type = "ralf"

    def __init__(
        self,
        dataset_name: RalfDatasetName = "cgl",
        task: RalfConfigTaskName = "unconditional",
        id2label: Mapping[int | str, str] | None = None,
        max_seq_length: int = 10,
        num_bin: int = 128,
        var_order: Sequence[RalfLayoutVariable] = DEFAULT_VAR_ORDER,
        special_tokens: Sequence[str] = DEFAULT_SPECIAL_TOKENS,
        geo_quantization: str = "linear",
        is_loc_vocab_shared: bool = False,
        d_model: int = 256,
        decoder_d_model: int = 256,
        encoder_layers: int = 6,
        decoder_layers: int = 6,
        num_attention_heads: int = 8,
        dropout: float = 0.1,
        retrieval_backbone: str = "dreamsim",
        saliency_k: int | str = "None",
        top_k: int = 16,
        use_reference_image: bool = False,
        layout_backbone: str = "feature_extractor",
        freeze_layout_encoder: bool = True,
        fusion: str = "concat_cross_attention",
        use_flag_embedding: bool = True,
        use_multitask: bool = False,
        global_task_embedding: bool = False,
        relation_size: int = 10,
        image_channels: int = 4,
        image_size: tuple[int, int] | list[int] | None = None,
        sort_order: Sequence[str] = ("label", "lexicographic"),
        retrieval_metadata: RalfConfigMetadata | None = None,
        original_config: RalfConfigMetadata | None = None,
        original_hydra_config: RalfConfigMetadata | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Initialize configuration values."""
        labels = (
            id2label_for_dataset(dataset_name)
            if id2label is None
            else {int(k): str(v) for k, v in id2label.items()}
        )

        self.dataset_name = dataset_name
        self.task = task
        self.id2label = labels
        self.max_seq_length = int(max_seq_length)
        self.num_bin = int(num_bin)
        self.var_order = tuple(var_order)
        self.special_tokens = tuple(special_tokens)
        self.geo_quantization = geo_quantization
        self.is_loc_vocab_shared = bool(is_loc_vocab_shared)

        self.d_model = int(d_model)
        self.decoder_d_model = int(decoder_d_model)
        self.encoder_layers = int(encoder_layers)
        self.decoder_layers = int(decoder_layers)
        self.num_attention_heads = int(num_attention_heads)
        self.dropout = float(dropout)

        self.retrieval_backbone = retrieval_backbone
        self.saliency_k = saliency_k
        self.top_k = int(top_k)
        self.use_reference_image = bool(use_reference_image)
        self.layout_backbone = layout_backbone
        self.freeze_layout_encoder = bool(freeze_layout_encoder)

        self.fusion = fusion
        self.use_flag_embedding = bool(use_flag_embedding)
        self.use_multitask = bool(use_multitask)
        self.global_task_embedding = bool(global_task_embedding)

        self.relation_size = int(relation_size)
        self.image_channels = int(image_channels)
        self.image_size = tuple(image_size) if image_size is not None else None
        self.sort_order = tuple(sort_order)
        self.retrieval_metadata = dict(retrieval_metadata or {})
        self.original_config = dict(original_config or original_hydra_config or {})
        self.original_hydra_config = self.original_config

        pad_token_id = self.special_token_id("pad")
        bos_token_id = self.special_token_id("bos")
        eos_token_id = self.special_token_id("eos")
        kwargs.pop("model_type", None)
        kwargs.pop("id2label", None)
        kwargs.pop("label2id", None)
        kwargs.pop("pad_token_id", None)
        kwargs.pop("bos_token_id", None)
        kwargs.pop("eos_token_id", None)

        super().__init__(
            id2label=self.id2label,
            label2id={label: idx for idx, label in self.id2label.items()},
        )
        self.pad_token_id = pad_token_id
        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id
        for key, value in kwargs.items():
            setattr(self, key, value)

    @property
    def num_bbox_tokens(self) -> int:
        """Return the number of geometry tokens."""
        return self.num_bin if self.is_loc_vocab_shared else self.num_bin * 4

    @property
    def vocab_size(self) -> int:
        """Return total autoregressive token vocabulary size."""
        return self.num_labels + self.num_bbox_tokens + len(self.special_tokens)

    @property
    def max_token_length(self) -> int:
        """Return maximum generated token length excluding BOS."""
        return self.max_seq_length * len(self.var_order)

    def special_token_id(self, name: str) -> int:
        """Return the numeric id for a special token name.

        Args:
            name: Special token name without brackets.

        Returns:
            Numeric token id.

        Raises:
            ValueError: If the token is absent from this config.
        """
        if name not in self.special_tokens:
            raise ValueError(f"Unknown special token: {name}")

        return self.num_labels + self.num_bbox_tokens + self.special_tokens.index(name)

    def bbox_token_offset(self, key: RalfLayoutVariable) -> int:
        """Return the first token id for a geometry variable."""
        if key == "label":
            return 0
        if self.is_loc_vocab_shared:
            return self.num_labels
        return self.num_labels + GEOMETRY_KEYS.index(key) * self.num_bin

num_bbox_tokens property

num_bbox_tokens: int

Return the number of geometry tokens.

vocab_size property

vocab_size: int

Return total autoregressive token vocabulary size.

max_token_length property

max_token_length: int

Return maximum generated token length excluding BOS.

__init__

__init__(
    dataset_name: RalfDatasetName = "cgl",
    task: RalfConfigTaskName = "unconditional",
    id2label: Mapping[int | str, str] | None = None,
    max_seq_length: int = 10,
    num_bin: int = 128,
    var_order: Sequence[
        RalfLayoutVariable
    ] = DEFAULT_VAR_ORDER,
    special_tokens: Sequence[str] = DEFAULT_SPECIAL_TOKENS,
    geo_quantization: str = "linear",
    is_loc_vocab_shared: bool = False,
    d_model: int = 256,
    decoder_d_model: int = 256,
    encoder_layers: int = 6,
    decoder_layers: int = 6,
    num_attention_heads: int = 8,
    dropout: float = 0.1,
    retrieval_backbone: str = "dreamsim",
    saliency_k: int | str = "None",
    top_k: int = 16,
    use_reference_image: bool = False,
    layout_backbone: str = "feature_extractor",
    freeze_layout_encoder: bool = True,
    fusion: str = "concat_cross_attention",
    use_flag_embedding: bool = True,
    use_multitask: bool = False,
    global_task_embedding: bool = False,
    relation_size: int = 10,
    image_channels: int = 4,
    image_size: tuple[int, int] | list[int] | None = None,
    sort_order: Sequence[str] = ("label", "lexicographic"),
    retrieval_metadata: RalfConfigMetadata | None = None,
    original_config: RalfConfigMetadata | None = None,
    original_hydra_config: RalfConfigMetadata | None = None,
    **kwargs: str | int | float | bool | None,
) -> None

Initialize configuration values.

Source code in models/ralf/src/ralf/configuration_ralf.py
 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
def __init__(
    self,
    dataset_name: RalfDatasetName = "cgl",
    task: RalfConfigTaskName = "unconditional",
    id2label: Mapping[int | str, str] | None = None,
    max_seq_length: int = 10,
    num_bin: int = 128,
    var_order: Sequence[RalfLayoutVariable] = DEFAULT_VAR_ORDER,
    special_tokens: Sequence[str] = DEFAULT_SPECIAL_TOKENS,
    geo_quantization: str = "linear",
    is_loc_vocab_shared: bool = False,
    d_model: int = 256,
    decoder_d_model: int = 256,
    encoder_layers: int = 6,
    decoder_layers: int = 6,
    num_attention_heads: int = 8,
    dropout: float = 0.1,
    retrieval_backbone: str = "dreamsim",
    saliency_k: int | str = "None",
    top_k: int = 16,
    use_reference_image: bool = False,
    layout_backbone: str = "feature_extractor",
    freeze_layout_encoder: bool = True,
    fusion: str = "concat_cross_attention",
    use_flag_embedding: bool = True,
    use_multitask: bool = False,
    global_task_embedding: bool = False,
    relation_size: int = 10,
    image_channels: int = 4,
    image_size: tuple[int, int] | list[int] | None = None,
    sort_order: Sequence[str] = ("label", "lexicographic"),
    retrieval_metadata: RalfConfigMetadata | None = None,
    original_config: RalfConfigMetadata | None = None,
    original_hydra_config: RalfConfigMetadata | None = None,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Initialize configuration values."""
    labels = (
        id2label_for_dataset(dataset_name)
        if id2label is None
        else {int(k): str(v) for k, v in id2label.items()}
    )

    self.dataset_name = dataset_name
    self.task = task
    self.id2label = labels
    self.max_seq_length = int(max_seq_length)
    self.num_bin = int(num_bin)
    self.var_order = tuple(var_order)
    self.special_tokens = tuple(special_tokens)
    self.geo_quantization = geo_quantization
    self.is_loc_vocab_shared = bool(is_loc_vocab_shared)

    self.d_model = int(d_model)
    self.decoder_d_model = int(decoder_d_model)
    self.encoder_layers = int(encoder_layers)
    self.decoder_layers = int(decoder_layers)
    self.num_attention_heads = int(num_attention_heads)
    self.dropout = float(dropout)

    self.retrieval_backbone = retrieval_backbone
    self.saliency_k = saliency_k
    self.top_k = int(top_k)
    self.use_reference_image = bool(use_reference_image)
    self.layout_backbone = layout_backbone
    self.freeze_layout_encoder = bool(freeze_layout_encoder)

    self.fusion = fusion
    self.use_flag_embedding = bool(use_flag_embedding)
    self.use_multitask = bool(use_multitask)
    self.global_task_embedding = bool(global_task_embedding)

    self.relation_size = int(relation_size)
    self.image_channels = int(image_channels)
    self.image_size = tuple(image_size) if image_size is not None else None
    self.sort_order = tuple(sort_order)
    self.retrieval_metadata = dict(retrieval_metadata or {})
    self.original_config = dict(original_config or original_hydra_config or {})
    self.original_hydra_config = self.original_config

    pad_token_id = self.special_token_id("pad")
    bos_token_id = self.special_token_id("bos")
    eos_token_id = self.special_token_id("eos")
    kwargs.pop("model_type", None)
    kwargs.pop("id2label", None)
    kwargs.pop("label2id", None)
    kwargs.pop("pad_token_id", None)
    kwargs.pop("bos_token_id", None)
    kwargs.pop("eos_token_id", None)

    super().__init__(
        id2label=self.id2label,
        label2id={label: idx for idx, label in self.id2label.items()},
    )
    self.pad_token_id = pad_token_id
    self.bos_token_id = bos_token_id
    self.eos_token_id = eos_token_id
    for key, value in kwargs.items():
        setattr(self, key, value)

special_token_id

special_token_id(name: str) -> int

Return the numeric id for a special token name.

Parameters:

Name Type Description Default
name str

Special token name without brackets.

required

Returns:

Type Description
int

Numeric token id.

Raises:

Type Description
ValueError

If the token is absent from this config.

Source code in models/ralf/src/ralf/configuration_ralf.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def special_token_id(self, name: str) -> int:
    """Return the numeric id for a special token name.

    Args:
        name: Special token name without brackets.

    Returns:
        Numeric token id.

    Raises:
        ValueError: If the token is absent from this config.
    """
    if name not in self.special_tokens:
        raise ValueError(f"Unknown special token: {name}")

    return self.num_labels + self.num_bbox_tokens + self.special_tokens.index(name)

bbox_token_offset

bbox_token_offset(key: RalfLayoutVariable) -> int

Return the first token id for a geometry variable.

Source code in models/ralf/src/ralf/configuration_ralf.py
231
232
233
234
235
236
237
def bbox_token_offset(self, key: RalfLayoutVariable) -> int:
    """Return the first token id for a geometry variable."""
    if key == "label":
        return 0
    if self.is_loc_vocab_shared:
        return self.num_labels
    return self.num_labels + GEOMETRY_KEYS.index(key) * self.num_bin

RalfImageProcessor

Bases: BaseImageProcessor

Prepare RGB poster images and one-channel saliency tensors.

Parameters:

Name Type Description Default
image_size tuple[int, int] | None

Optional (height, width) resize target.

None

Examples:

>>> processor = RalfImageProcessor(image_size=(8, 8))
>>> out = processor.preprocess([torch.zeros(3, 8, 8)])
>>> tuple(out["pixel_values"].shape)
(1, 3, 8, 8)
Source code in models/ralf/src/ralf/image_processing_ralf.py
 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
class RalfImageProcessor(BaseImageProcessor):
    """Prepare RGB poster images and one-channel saliency tensors.

    Args:
        image_size: Optional `(height, width)` resize target.

    Examples:
        >>> processor = RalfImageProcessor(image_size=(8, 8))
        >>> out = processor.preprocess([torch.zeros(3, 8, 8)])
        >>> tuple(out["pixel_values"].shape)
        (1, 3, 8, 8)
    """

    model_input_names = ["pixel_values", "saliency"]

    def __init__(
        self,
        image_size: tuple[int, int] | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Initialize image resize metadata."""
        super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
        self.image_size = tuple(image_size) if image_size is not None else None

    def preprocess(
        self,
        images: ImageInput | Sequence[ImageInput] | None,
        saliency: ImageInput | Sequence[ImageInput] | None = None,
        return_tensors: Literal["pt"] = "pt",
        **kwargs: str | int | float | bool | None,
    ) -> BatchFeature:
        """Convert images and saliency maps to tensors.

        Args:
            images: RGB images as PIL, NumPy, or torch tensors.
            saliency: Optional single-channel saliency maps.
            return_tensors: Tensor return format. Only `pt` is supported.
            kwargs: Reserved processor arguments.

        Returns:
            BatchFeature with `pixel_values` and `saliency`.

        Raises:
            ValueError: If `return_tensors` is not `pt`.
        """
        _ = kwargs
        if return_tensors != "pt":
            raise ValueError("RalfImageProcessor supports return_tensors='pt' only")

        image_items = (
            _as_list(images) if images is not None else [torch.zeros(3, 64, 64)]
        )
        pixel_values = torch.stack(
            [_image_to_tensor(item, channels=3) for item in image_items]
        )
        if self.image_size is not None:
            pixel_values = torch.nn.functional.interpolate(
                pixel_values,
                size=self.image_size,
                mode="bilinear",
                align_corners=False,
            )
        if saliency is None:
            saliency_values = torch.zeros(
                pixel_values.size(0),
                1,
                pixel_values.size(2),
                pixel_values.size(3),
                dtype=pixel_values.dtype,
            )
        else:
            saliency_items = _as_list(saliency)
            if len(saliency_items) == 1 and pixel_values.size(0) > 1:
                saliency_items = saliency_items * pixel_values.size(0)
            saliency_values = torch.stack(
                [_image_to_tensor(item, channels=1) for item in saliency_items]
            )
            if self.image_size is not None:
                saliency_values = torch.nn.functional.interpolate(
                    saliency_values,
                    size=self.image_size,
                    mode="bilinear",
                    align_corners=False,
                )
        return BatchFeature(
            {"pixel_values": pixel_values, "saliency": saliency_values},
            tensor_type=return_tensors,
        )

    def to_dict(self) -> dict[str, RalfImageProcessorConfigValue]:
        """Serialize image processor metadata."""
        data = cast(dict[str, RalfImageProcessorConfigValue], super().to_dict())
        data["image_size"] = self.image_size
        return data

__init__

__init__(
    image_size: tuple[int, int] | None = None,
    **kwargs: str | int | float | bool | None,
) -> None

Initialize image resize metadata.

Source code in models/ralf/src/ralf/image_processing_ralf.py
71
72
73
74
75
76
77
78
def __init__(
    self,
    image_size: tuple[int, int] | None = None,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Initialize image resize metadata."""
    super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
    self.image_size = tuple(image_size) if image_size is not None else None

preprocess

preprocess(
    images: ImageInput | Sequence[ImageInput] | None,
    saliency: ImageInput
    | Sequence[ImageInput]
    | None = None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: str | int | float | bool | None,
) -> BatchFeature

Convert images and saliency maps to tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

RGB images as PIL, NumPy, or torch tensors.

required
saliency ImageInput | Sequence[ImageInput] | None

Optional single-channel saliency maps.

None
return_tensors Literal['pt']

Tensor return format. Only pt is supported.

'pt'
kwargs str | int | float | bool | None

Reserved processor arguments.

{}

Returns:

Type Description
BatchFeature

BatchFeature with pixel_values and saliency.

Raises:

Type Description
ValueError

If return_tensors is not pt.

Source code in models/ralf/src/ralf/image_processing_ralf.py
 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
def preprocess(
    self,
    images: ImageInput | Sequence[ImageInput] | None,
    saliency: ImageInput | Sequence[ImageInput] | None = None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: str | int | float | bool | None,
) -> BatchFeature:
    """Convert images and saliency maps to tensors.

    Args:
        images: RGB images as PIL, NumPy, or torch tensors.
        saliency: Optional single-channel saliency maps.
        return_tensors: Tensor return format. Only `pt` is supported.
        kwargs: Reserved processor arguments.

    Returns:
        BatchFeature with `pixel_values` and `saliency`.

    Raises:
        ValueError: If `return_tensors` is not `pt`.
    """
    _ = kwargs
    if return_tensors != "pt":
        raise ValueError("RalfImageProcessor supports return_tensors='pt' only")

    image_items = (
        _as_list(images) if images is not None else [torch.zeros(3, 64, 64)]
    )
    pixel_values = torch.stack(
        [_image_to_tensor(item, channels=3) for item in image_items]
    )
    if self.image_size is not None:
        pixel_values = torch.nn.functional.interpolate(
            pixel_values,
            size=self.image_size,
            mode="bilinear",
            align_corners=False,
        )
    if saliency is None:
        saliency_values = torch.zeros(
            pixel_values.size(0),
            1,
            pixel_values.size(2),
            pixel_values.size(3),
            dtype=pixel_values.dtype,
        )
    else:
        saliency_items = _as_list(saliency)
        if len(saliency_items) == 1 and pixel_values.size(0) > 1:
            saliency_items = saliency_items * pixel_values.size(0)
        saliency_values = torch.stack(
            [_image_to_tensor(item, channels=1) for item in saliency_items]
        )
        if self.image_size is not None:
            saliency_values = torch.nn.functional.interpolate(
                saliency_values,
                size=self.image_size,
                mode="bilinear",
                align_corners=False,
            )
    return BatchFeature(
        {"pixel_values": pixel_values, "saliency": saliency_values},
        tensor_type=return_tensors,
    )

to_dict

to_dict() -> dict[str, RalfImageProcessorConfigValue]

Serialize image processor metadata.

Source code in models/ralf/src/ralf/image_processing_ralf.py
145
146
147
148
149
def to_dict(self) -> dict[str, RalfImageProcessorConfigValue]:
    """Serialize image processor metadata."""
    data = cast(dict[str, RalfImageProcessorConfigValue], super().to_dict())
    data["image_size"] = self.image_size
    return data

RalfForConditionalLayoutGeneration

Bases: PreTrainedModel

Standalone PreTrainedModel for RALF autoregressive decoding.

Source code in models/ralf/src/ralf/modeling_ralf.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
class RalfForConditionalLayoutGeneration(PreTrainedModel):
    """Standalone `PreTrainedModel` for RALF autoregressive decoding."""

    config_class = RalfConfig
    base_model_prefix = "ralf"
    main_input_name = "input_ids"
    _tied_weights_keys: dict[str, str] = {}

    flag_img: Int[torch.Tensor, "1"]
    flag_user_const: Int[torch.Tensor, "1"]

    def __init__(self, config: RalfConfig) -> None:
        """Initialize a local module tree matching original RALF checkpoint keys."""
        super().__init__(config)
        self.tokenizer = RalfTokenizerView(config)
        self.dataset_name = config.dataset_name
        self.d_model = config.d_model
        self.max_seq_length = config.max_seq_length

        self.use_reference_image = config.use_reference_image
        self.layout_backbone = config.layout_backbone
        self.top_k = config.top_k
        self.weight_init = True

        self.retrieval_backbone = config.retrieval_backbone
        self.random_retrieval = False
        self.saliency_k = str(config.saliency_k)

        self.num_layers = config.encoder_layers
        self.nhead = config.num_attention_heads
        self.dropout = config.dropout

        self.encoder = ResnetFeatureExtractor(
            backbone="resnet50", d_model=config.d_model, head="transformer"
        )
        self.pos_emb_2d = PositionEmbeddingSine(config.d_model, normalize=True)
        self.dim_feedforward = 4 * config.d_model
        self.transformer_encoder = nn.TransformerEncoder(
            encoder_layer=nn.TransformerEncoderLayer(
                d_model=config.d_model,
                nhead=config.num_attention_heads,
                batch_first=True,
                dropout=config.dropout,
                norm_first=True,
                dim_feedforward=self.dim_feedforward,
            ),
            num_layers=config.encoder_layers,
        )
        self.decoder = BaseDecoder(
            d_label=self.tokenizer.N_total,
            d_model=config.decoder_d_model,
            num_layers=config.decoder_layers,
            nhead=config.num_attention_heads,
            pos_emb="layout",
            dim_feedforward=self.dim_feedforward,
        )
        self.loss_fn_ce = nn.CrossEntropyLoss(
            label_smoothing=0.1, ignore_index=self.tokenizer.name_to_id("pad")
        )
        self.layout_encoer = FIDNetFeatureExtractor(
            num_label=self.tokenizer.N_label,
            d_model=256,
            nhead=4,
            num_layers=4,
            max_bbox=config.max_seq_length,
        )
        self.layout_encoer.enc_transformer.token.requires_grad = False
        for parameter in self.layout_encoer.parameters():
            parameter.requires_grad = False
        self.pos_emb_1d = PositionalEncoding1d(
            d_model=config.d_model,
            max_len=5000 if not config.use_reference_image else 10000,
        )
        self.layout_adapter = FeedForward(
            dim=256, hidden_dim=4 * config.d_model, output_dim=config.d_model
        )
        self.head = FeedForward(dim=config.d_model, hidden_dim=4 * config.d_model)
        self.auxilary_task = self._canonical_to_task_name(config.task)
        self.use_multitask = config.use_multitask
        self.global_task_embedding = config.global_task_embedding
        self.preprocessor = RalfTaskPreprocessor(
            tokenizer=self.tokenizer,
            task=self.auxilary_task,
            global_task_embedding=config.global_task_embedding,
        )
        self.user_const_encoder = UserConstraintTransformerEncoder(
            d_model=config.d_model,
            nhead=config.num_attention_heads,
            num_layers=config.encoder_layers,
            d_label=self.preprocessor.N_total,
            dim_feedforward=self.dim_feedforward,
        )
        self.use_flag_embedding = config.use_flag_embedding
        if self.use_flag_embedding:
            self.task_emb = nn.Embedding(2, 1)
            nn.init.normal_(self.task_emb.weight, mean=0.0, std=0.02)
            self.register_buffer("flag_img", torch.zeros(1).long())
            self.register_buffer("flag_user_const", torch.ones(1).long())
        self.attn = Attention(
            config.d_model, config.d_model, heads=8, dim_head=64, dropout=0.0
        )
        self.all_tied_weights_keys = dict(self._tied_weights_keys)

    @staticmethod
    def _canonical_to_task_name(task: RalfConfigTaskName | str) -> RalfTaskName:
        if task not in TASK_BY_CONDITION:
            raise ValueError(f"Unsupported RALF task or condition: {task}")

        return TASK_BY_CONDITION[cast(RalfConfigTaskName, task)]

    def _default_retrieved(
        self, batch_size: int, device: torch.device, dtype: torch.dtype
    ) -> dict[str, Shaped[torch.Tensor, ...]]:
        shape = (batch_size, self.config.top_k, self.config.max_seq_length)
        image = torch.zeros(
            batch_size, self.config.top_k, 4, 64, 64, device=device, dtype=dtype
        )
        return {
            "image": image,
            "center_x": torch.zeros(shape, device=device, dtype=dtype),
            "center_y": torch.zeros(shape, device=device, dtype=dtype),
            "width": torch.zeros(shape, device=device, dtype=dtype),
            "height": torch.zeros(shape, device=device, dtype=dtype),
            "label": torch.zeros(shape, device=device, dtype=torch.long),
            "mask": torch.zeros(shape, device=device, dtype=torch.bool),
        }

    def _encode_into_memory(
        self,
        inputs: Mapping[
            str, Shaped[torch.Tensor, ...] | Mapping[str, Shaped[torch.Tensor, ...]]
        ],
    ) -> dict[str, Float[torch.Tensor, "batch memory_tokens channels"]]:
        image = cast(Tensor, inputs["image"])
        retrieved = cast(Mapping[str, Shaped[torch.Tensor, "..."]], inputs["retrieved"])
        input_img_feature = self.encoder(image)
        input_img_feature = self.pos_emb_2d(input_img_feature)
        image_memory = self.transformer_encoder(input_img_feature)
        ref_layouts = _extract_retrieved_features(
            retrieved_samples=retrieved,
            top_k=self.top_k,
            layout_encoder=self.layout_encoer,
            layout_adapter=self.layout_adapter,
            pos_emb_1d=self.pos_emb_1d,
        )
        memory_ca = self.attn(image_memory, ref_layouts)
        img_retrieved_layout_memory = self.head(
            torch.cat([image_memory, memory_ca, ref_layouts], dim=1)
        )
        if self.global_task_embedding:
            task_token = self.preprocessor.get_token(
                self.preprocessor.TASK, img_retrieved_layout_memory.size(0)
            ).type_as(cast(Tensor, inputs["seq_layout_const"]))
        else:
            task_token = None
        user_const_feature = self.user_const_encoder(
            src=cast(Tensor, inputs["seq_layout_const"]),
            src_key_padding_mask=cast(Tensor, inputs["seq_layout_const_pad_mask"]),
            task_token=task_token,
        )
        if self.use_flag_embedding:
            img_retrieved_layout_memory = img_retrieved_layout_memory + self.task_emb(
                self.flag_img
            )
            user_const_feature = user_const_feature + self.task_emb(
                self.flag_user_const
            )
        return {
            "memory": torch.cat(
                [img_retrieved_layout_memory, user_const_feature], dim=1
            )
        }

    def _prepare_conditional_inputs(
        self,
        *,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None,
        retrieved: RalfRetrievedBatch | None,
        batch_size: int,
        condition_type: RalfConfigTaskName | None = None,
        constraint_input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
        constraint_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
        relationship_table: RalfRelationshipTable | None = None,
        sample_ids: Int[torch.Tensor, "batch"]
        | Sequence[int | str]
        | int
        | str
        | None = None,
    ) -> dict[str, Shaped[torch.Tensor, ...] | Mapping[str, Shaped[torch.Tensor, ...]]]:
        device = next(self.parameters()).device
        dtype = next(self.parameters()).dtype
        if pixel_values is None:
            pixel_values = torch.zeros(
                batch_size, 3, 64, 64, device=device, dtype=dtype
            )
        if saliency is None:
            saliency = torch.zeros(
                pixel_values.size(0),
                1,
                pixel_values.size(2),
                pixel_values.size(3),
                device=pixel_values.device,
                dtype=pixel_values.dtype,
            )
        if pixel_values.size(-1) < 64 or pixel_values.size(-2) < 64:
            pixel_values = F.interpolate(
                pixel_values, size=(64, 64), mode="bilinear", align_corners=False
            )
            saliency = F.interpolate(
                saliency, size=(64, 64), mode="bilinear", align_corners=False
            )
        if pixel_values.size(0) == 1 and batch_size > 1:
            pixel_values = pixel_values.expand(batch_size, -1, -1, -1)
            saliency = saliency.expand(batch_size, -1, -1, -1)
        image = torch.cat([pixel_values, saliency], dim=1).to(
            device=device, dtype=dtype
        )
        retrieved_dict = (
            self._default_retrieved(image.size(0), device, dtype)
            if retrieved is None
            else {
                key: value.to(device=device, dtype=dtype)
                if value.is_floating_point()
                else value.to(device=device)
                for key, value in retrieved_batch_to_model_inputs(retrieved).items()
            }
        )
        if retrieved_dict["image"].size(2) == 3:
            retrieved_dict["image"] = torch.cat(
                [retrieved_dict["image"], retrieved_dict["saliency"]], dim=2
            )
        task = self._canonical_to_task_name(condition_type or self.auxilary_task)
        preprocessor = (
            self.preprocessor
            if task == self.auxilary_task and relationship_table is None
            else RalfTaskPreprocessor(
                tokenizer=self.tokenizer,
                task=task,
                global_task_embedding=self.global_task_embedding,
                relationship_table=relationship_table if task == "relation" else None,
                relation_size=self.config.relation_size,
            )
        )
        cond = RalfConditionalInputs(
            image=image,
            retrieved=retrieved_dict,
            seq=constraint_input_ids,
            mask=constraint_mask,
            element_mask=constraint_element_mask,
            task=task,
            id=sample_ids,
        )
        seq_constraints = preprocessor(cond)
        return {
            "image": image,
            "retrieved": retrieved_dict,
            "seq_layout_const": seq_constraints["seq"],
            "seq_layout_const_pad_mask": seq_constraints["pad_mask"],
        }

    def _prepare_unconditional_inputs(
        self,
        *,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None,
        retrieved: RalfRetrievedBatch | None,
        batch_size: int,
    ) -> dict[str, Shaped[torch.Tensor, ...] | Mapping[str, Shaped[torch.Tensor, ...]]]:
        return self._prepare_conditional_inputs(
            pixel_values=pixel_values,
            saliency=saliency,
            retrieved=retrieved,
            batch_size=batch_size,
            condition_type="uncond",
        )

    def forward(
        self,
        input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None = None,
        attention_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        labels: Int[torch.Tensor, "batch tokens"] | None = None,
        retrieved: RalfRetrievedBatch | None = None,
        condition_type: RalfConfigTaskName | None = None,
        constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
        return_dict: bool | None = None,
        **kwargs: str | float | bool | None,
    ) -> CausalLMOutput | tuple[Float[torch.Tensor, ...], ...]:
        """Run teacher-forced token prediction using the local RALF port."""
        relationship_table = cast(
            RalfRelationshipTable | None, kwargs.get("relationship_table")
        )
        sample_ids = cast(
            Int[torch.Tensor, "batch"] | Sequence[int | str] | int | str | None,
            kwargs.get("sample_ids"),
        )
        if input_ids is None:
            raise ValueError("input_ids is required")

        encoder_inputs = self._prepare_conditional_inputs(
            pixel_values=pixel_values,
            saliency=saliency,
            retrieved=retrieved,
            batch_size=input_ids.size(0),
            condition_type=condition_type,
            constraint_input_ids=input_ids,
            constraint_mask=attention_mask,
            constraint_element_mask=constraint_element_mask,
            relationship_table=relationship_table,
            sample_ids=sample_ids,
        )
        encoded_feat = self._encode_into_memory(encoder_inputs)
        logits = self.decoder(
            tgt=input_ids,
            tgt_key_padding_mask=None
            if attention_mask is None
            else ~attention_mask.bool(),
            is_causal=True,
            **encoded_feat,
        )
        loss = None
        if labels is not None:
            targets = labels.clone()
            targets[targets == self.config.pad_token_id] = -100
            loss = F.cross_entropy(
                logits.reshape(-1, logits.size(-1)),
                targets.reshape(-1),
                ignore_index=-100,
            )
        if return_dict is False:
            return (logits,) if loss is None else (loss, logits)
        return CausalLMOutput(loss=cast(torch.FloatTensor | None, loss), logits=logits)

    @torch.no_grad()
    def _generate_sequences(
        self,
        input_ids: Int[torch.Tensor, "batch tokens"],
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None = None,
        attention_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        *,
        max_length: int | None = None,
        temperature: float = 1.0,
        top_k: int | None = None,
        generator: torch.Generator | None = None,
        token_mask: Bool[torch.Tensor, "tokens vocab"] | None = None,
        retrieved: RalfRetrievedBatch | None = None,
        condition_type: RalfConfigTaskName | None = None,
        constraint_input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
        constraint_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
        relationship_table: RalfRelationshipTable | None = None,
        sample_ids: Int[torch.Tensor, "batch"]
        | Sequence[int | str]
        | int
        | str
        | None = None,
    ) -> Int[torch.Tensor, "batch tokens"]:
        """Run the RALF autoregressive token loop used by `RalfPipeline`."""
        _ = attention_mask
        was_training = self.training
        self.eval()
        task = self._canonical_to_task_name(condition_type or self.auxilary_task)
        generated = input_ids[:, :1].clone()
        start_step = 0
        if task == "partial":
            condition_seq = (
                constraint_input_ids if constraint_input_ids is not None else input_ids
            )
            prefix = condition_seq[:, 1 : 1 + len(self.config.var_order)]
            generated = torch.cat([generated, prefix.to(generated.device)], dim=1)
            start_step = len(self.config.var_order)
        max_length = max_length or self.config.max_token_length
        encoder_inputs = self._prepare_conditional_inputs(
            pixel_values=pixel_values,
            saliency=saliency,
            retrieved=retrieved,
            batch_size=input_ids.size(0),
            condition_type=task,
            constraint_input_ids=constraint_input_ids,
            constraint_mask=constraint_mask,
            constraint_element_mask=constraint_element_mask,
            relationship_table=relationship_table,
            sample_ids=sample_ids,
        )
        encoded_feat = self._encode_into_memory(encoder_inputs)
        try:
            for step in range(start_step, max_length):
                logits = self.decoder(
                    tgt=generated,
                    tgt_key_padding_mask=generated.eq(self.config.pad_token_id),
                    is_causal=True,
                    **encoded_feat,
                )
                next_logits = logits[:, step : step + 1]
                next_logits = rearrange(next_logits, "b 1 c -> b c") / temperature
                if token_mask is not None and step < token_mask.size(0):
                    next_logits = next_logits.masked_fill(
                        ~token_mask[step].to(next_logits.device), -math.inf
                    )
                next_logits = _apply_decode_space_restriction(
                    task=task,
                    step=step,
                    condition=constraint_input_ids,
                    logits=next_logits,
                    pad_id=self.config.pad_token_id,
                    eos_id=self.config.eos_token_id,
                    max_length=self.config.max_token_length,
                )
                if top_k is not None and top_k > 0 and top_k < next_logits.size(-1):
                    values = torch.topk(next_logits, top_k).values
                    next_logits = next_logits.masked_fill(
                        next_logits < values[:, [-1]], -math.inf
                    )
                probs = F.softmax(next_logits, dim=-1)
                next_token = torch.multinomial(
                    probs, num_samples=1, generator=generator
                )
                generated = torch.cat([generated, next_token], dim=1)
        finally:
            if was_training:
                self.train()
        return generated

__init__

__init__(config: RalfConfig) -> None

Initialize a local module tree matching original RALF checkpoint keys.

Source code in models/ralf/src/ralf/modeling_ralf.py
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def __init__(self, config: RalfConfig) -> None:
    """Initialize a local module tree matching original RALF checkpoint keys."""
    super().__init__(config)
    self.tokenizer = RalfTokenizerView(config)
    self.dataset_name = config.dataset_name
    self.d_model = config.d_model
    self.max_seq_length = config.max_seq_length

    self.use_reference_image = config.use_reference_image
    self.layout_backbone = config.layout_backbone
    self.top_k = config.top_k
    self.weight_init = True

    self.retrieval_backbone = config.retrieval_backbone
    self.random_retrieval = False
    self.saliency_k = str(config.saliency_k)

    self.num_layers = config.encoder_layers
    self.nhead = config.num_attention_heads
    self.dropout = config.dropout

    self.encoder = ResnetFeatureExtractor(
        backbone="resnet50", d_model=config.d_model, head="transformer"
    )
    self.pos_emb_2d = PositionEmbeddingSine(config.d_model, normalize=True)
    self.dim_feedforward = 4 * config.d_model
    self.transformer_encoder = nn.TransformerEncoder(
        encoder_layer=nn.TransformerEncoderLayer(
            d_model=config.d_model,
            nhead=config.num_attention_heads,
            batch_first=True,
            dropout=config.dropout,
            norm_first=True,
            dim_feedforward=self.dim_feedforward,
        ),
        num_layers=config.encoder_layers,
    )
    self.decoder = BaseDecoder(
        d_label=self.tokenizer.N_total,
        d_model=config.decoder_d_model,
        num_layers=config.decoder_layers,
        nhead=config.num_attention_heads,
        pos_emb="layout",
        dim_feedforward=self.dim_feedforward,
    )
    self.loss_fn_ce = nn.CrossEntropyLoss(
        label_smoothing=0.1, ignore_index=self.tokenizer.name_to_id("pad")
    )
    self.layout_encoer = FIDNetFeatureExtractor(
        num_label=self.tokenizer.N_label,
        d_model=256,
        nhead=4,
        num_layers=4,
        max_bbox=config.max_seq_length,
    )
    self.layout_encoer.enc_transformer.token.requires_grad = False
    for parameter in self.layout_encoer.parameters():
        parameter.requires_grad = False
    self.pos_emb_1d = PositionalEncoding1d(
        d_model=config.d_model,
        max_len=5000 if not config.use_reference_image else 10000,
    )
    self.layout_adapter = FeedForward(
        dim=256, hidden_dim=4 * config.d_model, output_dim=config.d_model
    )
    self.head = FeedForward(dim=config.d_model, hidden_dim=4 * config.d_model)
    self.auxilary_task = self._canonical_to_task_name(config.task)
    self.use_multitask = config.use_multitask
    self.global_task_embedding = config.global_task_embedding
    self.preprocessor = RalfTaskPreprocessor(
        tokenizer=self.tokenizer,
        task=self.auxilary_task,
        global_task_embedding=config.global_task_embedding,
    )
    self.user_const_encoder = UserConstraintTransformerEncoder(
        d_model=config.d_model,
        nhead=config.num_attention_heads,
        num_layers=config.encoder_layers,
        d_label=self.preprocessor.N_total,
        dim_feedforward=self.dim_feedforward,
    )
    self.use_flag_embedding = config.use_flag_embedding
    if self.use_flag_embedding:
        self.task_emb = nn.Embedding(2, 1)
        nn.init.normal_(self.task_emb.weight, mean=0.0, std=0.02)
        self.register_buffer("flag_img", torch.zeros(1).long())
        self.register_buffer("flag_user_const", torch.ones(1).long())
    self.attn = Attention(
        config.d_model, config.d_model, heads=8, dim_head=64, dropout=0.0
    )
    self.all_tied_weights_keys = dict(self._tied_weights_keys)

forward

forward(
    input_ids: Int[Tensor, "batch tokens"] | None = None,
    pixel_values: Float[
        Tensor, "batch channels height width"
    ]
    | None = None,
    saliency: Float[Tensor, "batch 1 height width"]
    | None = None,
    attention_mask: Bool[Tensor, "batch tokens"]
    | None = None,
    labels: Int[Tensor, "batch tokens"] | None = None,
    retrieved: RalfRetrievedBatch | None = None,
    condition_type: RalfConfigTaskName | None = None,
    constraint_element_mask: Bool[Tensor, "batch elements"]
    | None = None,
    return_dict: bool | None = None,
    **kwargs: str | float | bool | None,
) -> CausalLMOutput | tuple[Float[torch.Tensor, ...], ...]

Run teacher-forced token prediction using the local RALF port.

Source code in models/ralf/src/ralf/modeling_ralf.py
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
def forward(
    self,
    input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
    pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
    saliency: Float[torch.Tensor, "batch 1 height width"] | None = None,
    attention_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
    labels: Int[torch.Tensor, "batch tokens"] | None = None,
    retrieved: RalfRetrievedBatch | None = None,
    condition_type: RalfConfigTaskName | None = None,
    constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
    return_dict: bool | None = None,
    **kwargs: str | float | bool | None,
) -> CausalLMOutput | tuple[Float[torch.Tensor, ...], ...]:
    """Run teacher-forced token prediction using the local RALF port."""
    relationship_table = cast(
        RalfRelationshipTable | None, kwargs.get("relationship_table")
    )
    sample_ids = cast(
        Int[torch.Tensor, "batch"] | Sequence[int | str] | int | str | None,
        kwargs.get("sample_ids"),
    )
    if input_ids is None:
        raise ValueError("input_ids is required")

    encoder_inputs = self._prepare_conditional_inputs(
        pixel_values=pixel_values,
        saliency=saliency,
        retrieved=retrieved,
        batch_size=input_ids.size(0),
        condition_type=condition_type,
        constraint_input_ids=input_ids,
        constraint_mask=attention_mask,
        constraint_element_mask=constraint_element_mask,
        relationship_table=relationship_table,
        sample_ids=sample_ids,
    )
    encoded_feat = self._encode_into_memory(encoder_inputs)
    logits = self.decoder(
        tgt=input_ids,
        tgt_key_padding_mask=None
        if attention_mask is None
        else ~attention_mask.bool(),
        is_causal=True,
        **encoded_feat,
    )
    loss = None
    if labels is not None:
        targets = labels.clone()
        targets[targets == self.config.pad_token_id] = -100
        loss = F.cross_entropy(
            logits.reshape(-1, logits.size(-1)),
            targets.reshape(-1),
            ignore_index=-100,
        )
    if return_dict is False:
        return (logits,) if loss is None else (loss, logits)
    return CausalLMOutput(loss=cast(torch.FloatTensor | None, loss), logits=logits)

RalfPipeline

Bases: LayoutGenerationPipeline

Compose a RALF model and processor for content-aware retrieval generation.

Source code in models/ralf/src/ralf/pipeline_ralf.py
 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
class RalfPipeline(LayoutGenerationPipeline):
    """Compose a RALF model and processor for content-aware retrieval generation."""

    config_class: ClassVar[type[PretrainedConfig]] = RalfConfig
    component_specs: ClassVar[dict[str, PipelineComponentSpec]] = {
        "model": PipelineComponentSpec(
            attribute_name="model",
            loader=_load_model_component,
            marker_file="config.json",
        ),
        "processor": PipelineComponentSpec(
            attribute_name="processor",
            loader=_load_processor_component,
            marker_file="processor_config.json",
            save_with_is_main_process=False,
        ),
    }

    config: RalfConfig
    model: RalfForConditionalLayoutGeneration
    processor: RalfProcessor

    def __init__(
        self,
        model: RalfForConditionalLayoutGeneration,
        processor: RalfProcessor | None = None,
        config: RalfConfig | None = None,
    ) -> None:
        """Initialize the RALF pipeline."""
        super().__init__(config or model.config)
        self.config = config or model.config
        self.model = model
        self.processor = processor or RalfProcessor.from_config(self.config)

    @classmethod
    def _from_pretrained_components(
        cls,
        *,
        config: PretrainedConfig,
        components: Mapping[str, RalfPipelineComponent | None],
    ) -> "RalfPipeline":
        """Build a pipeline from checkpoint components."""
        return cls(
            config=cast(RalfConfig, config),
            model=cast(RalfForConditionalLayoutGeneration, components["model"]),
            processor=cast(RalfProcessor, components["processor"]),
        )

    @torch.no_grad()
    def __call__(  # ty: ignore[invalid-method-override]
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        saliency: ImageInput | Sequence[ImageInput] | None = None,
        batch_size: int = 1,
        seed: int | None = None,
        generator: torch.Generator | None = None,
        condition_type: ConditionType | str = ConditionType.unconditional,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[bool]
        | Sequence[Sequence[bool]]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        retrieved_layouts: Mapping[
            str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
        ]
        | None = None,
        retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
        retrieved_saliency: RalfSequenceInput
        | Shaped[torch.Tensor, "..."]
        | None = None,
        retrieved_indexes: Int[torch.Tensor, "batch candidates"]
        | Sequence[Sequence[int]]
        | None = None,
        retrieval: Mapping[
            str,
            RalfRetrievalValue
            | Shaped[torch.Tensor, "..."]
            | Mapping[str, Shaped[torch.Tensor, "..."]],
        ]
        | None = None,
        retrieval_table: RalfRetrievalTable | None = None,
        query_ids: Sequence[int | str] | None = None,
        relations: RalfRelationshipTable | None = None,
        num_inference_steps: int | None = None,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        return_intermediates: bool = False,
        temperature: float = 1.0,
        top_k: int | None = None,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Shaped[torch.Tensor, "..."]
            | dict[int, str]
            | Mapping[str, Shaped[torch.Tensor, "..."]]
            | None,
        ]
    ):
        """Generate layouts through the RALF public interface.

        Args:
            images: Poster/content images. When omitted, the pipeline uses a
                zero image for smoke/debug calls; converted checkpoints were
                trained with real content inputs.
            saliency: Optional saliency maps.
            batch_size: Batch size when images are absent.
            seed: Convenience seed used only when `generator` is absent.
            generator: PyTorch generator; takes precedence over `seed`.
            condition_type: Canonical condition type or alias.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Optional requested element counts.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size for pixel boxes.
            retrieved_layouts: Explicit retrieved layouts. When no retrieval data is
                supplied, the model receives zero retrieval memory for smoke/debug
                calls rather than paper-equivalent retrieved examples.
            retrieved_images: Explicit retrieved images.
            retrieved_saliency: Explicit retrieved saliency maps.
            retrieved_indexes: Explicit retrieved indexes.
            retrieval: Canonical v2 retrieval container.
            retrieval_table: Optional model-side retrieval table.
            query_ids: Query ids used for table lookup when explicit examples are absent.
            relations: Optional relation constraints.
            num_inference_steps: Reserved v1 argument.
            output_type: `dataclass` or `dict`.
            return_intermediates: Whether to return retrieval debug metadata.
            temperature: Sampling temperature.
            top_k: Optional top-k sampling limit.

        Returns:
            LayoutGenerationOutput or dictionary.
        """
        _ = (num_elements, num_inference_steps)
        condition = normalize_condition_type(condition_type)
        if condition not in SUPPORTED_GENERATION_CONDITIONS:
            raise NotImplementedError(
                "This RALF port currently supports unconditional, label, "
                "label_size, completion, refinement, relation, retrieval, and "
                "content_image; "
                f"got {condition}"
            )

        encoded = self.processor(
            images=images,
            saliency=saliency,
            condition_type=condition,
            labels=labels,
            bbox=bbox,
            mask=mask,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
            retrieved_layouts=retrieved_layouts,
            retrieved_images=retrieved_images,
            retrieved_saliency=retrieved_saliency,
            retrieved_indexes=retrieved_indexes,
            retrieval=retrieval,
            batch_size=batch_size,
        )
        model_device = next(self.model.parameters()).device
        generation_generator = self.prepare_generator(
            generator=generator,
            seed=seed,
            device=model_device,
        )
        intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]] = {}
        if "retrieval" in encoded:
            retrieval_batch = encoded["retrieval"]
            if retrieval_batch.indexes is not None:
                intermediates["retrieval"] = {"indexes": retrieval_batch.indexes}
        elif retrieval_table is not None and query_ids is not None:
            intermediates["retrieval"] = {"indexes": retrieval_table.lookup(query_ids)}
        sequences = self.model._generate_sequences(
            encoded["input_ids"].to(model_device),
            pixel_values=encoded["pixel_values"].to(model_device),
            saliency=encoded["saliency"].to(model_device),
            attention_mask=encoded["attention_mask"].to(model_device),
            max_length=self.config.max_token_length,
            temperature=temperature,
            top_k=top_k,
            generator=generation_generator,
            token_mask=self.processor.layout_tokenizer.token_mask(model_device),
            retrieved=encoded.get("retrieval"),
            condition_type=cast(RalfConfigTaskName, str(condition)),
            constraint_input_ids=encoded["input_ids"].to(model_device),
            constraint_mask=encoded["attention_mask"].to(model_device),
            constraint_element_mask=encoded["constraint_mask"].to(model_device),
            relationship_table=relations,
            sample_ids=query_ids,
        )
        return self.processor.post_process_layouts(
            sequences.cpu(),
            output_type=output_type,
            intermediates=intermediates if return_intermediates else None,
        )

    generate = __call__

__init__

__init__(
    model: RalfForConditionalLayoutGeneration,
    processor: RalfProcessor | None = None,
    config: RalfConfig | None = None,
) -> None

Initialize the RALF pipeline.

Source code in models/ralf/src/ralf/pipeline_ralf.py
112
113
114
115
116
117
118
119
120
121
122
def __init__(
    self,
    model: RalfForConditionalLayoutGeneration,
    processor: RalfProcessor | None = None,
    config: RalfConfig | None = None,
) -> None:
    """Initialize the RALF pipeline."""
    super().__init__(config or model.config)
    self.config = config or model.config
    self.model = model
    self.processor = processor or RalfProcessor.from_config(self.config)

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput
    | Sequence[ImageInput]
    | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: Generator | None = None,
    condition_type: ConditionType
    | str = ConditionType.unconditional,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | RalfSequenceInput
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[Tensor, "..."]
        | Mapping[str, Shaped[Tensor, "..."]],
    ]
    | None = None,
    retrieval_table: RalfRetrievalTable | None = None,
    query_ids: Sequence[int | str] | None = None,
    relations: RalfRelationshipTable | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    temperature: float = 1.0,
    top_k: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
)

Generate layouts through the RALF public interface.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster/content images. When omitted, the pipeline uses a zero image for smoke/debug calls; converted checkpoints were trained with real content inputs.

None
saliency ImageInput | Sequence[ImageInput] | None

Optional saliency maps.

None
batch_size int

Batch size when images are absent.

1
seed int | None

Convenience seed used only when generator is absent.

None
generator Generator | None

PyTorch generator; takes precedence over seed.

None
condition_type ConditionType | str

Canonical condition type or alias.

unconditional
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | RalfSequenceInput | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[bool] | Sequence[Sequence[bool]] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element counts.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size for pixel boxes.

None
retrieved_layouts Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...']] | None

Explicit retrieved layouts. When no retrieval data is supplied, the model receives zero retrieval memory for smoke/debug calls rather than paper-equivalent retrieved examples.

None
retrieved_images RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved images.

None
retrieved_saliency RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved saliency maps.

None
retrieved_indexes Int[Tensor, 'batch candidates'] | Sequence[Sequence[int]] | None

Explicit retrieved indexes.

None
retrieval Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...'] | Mapping[str, Shaped[Tensor, '...']]] | None

Canonical v2 retrieval container.

None
retrieval_table RalfRetrievalTable | None

Optional model-side retrieval table.

None
query_ids Sequence[int | str] | None

Query ids used for table lookup when explicit examples are absent.

None
relations RalfRelationshipTable | None

Optional relation constraints.

None
num_inference_steps int | None

Reserved v1 argument.

None
output_type Literal['dataclass', 'dict']

dataclass or dict.

'dataclass'
return_intermediates bool

Whether to return retrieval debug metadata.

False
temperature float

Sampling temperature.

1.0
top_k int | None

Optional top-k sampling limit.

None

Returns:

Type Description
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...'] | dict[int, str] | Mapping[str, Shaped[Tensor, '...']] | None]

LayoutGenerationOutput or dictionary.

Source code in models/ralf/src/ralf/pipeline_ralf.py
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
@torch.no_grad()
def __call__(  # ty: ignore[invalid-method-override]
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput | Sequence[ImageInput] | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: torch.Generator | None = None,
    condition_type: ConditionType | str = ConditionType.unconditional,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[torch.Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[torch.Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[torch.Tensor, "..."]
        | Mapping[str, Shaped[torch.Tensor, "..."]],
    ]
    | None = None,
    retrieval_table: RalfRetrievalTable | None = None,
    query_ids: Sequence[int | str] | None = None,
    relations: RalfRelationshipTable | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    temperature: float = 1.0,
    top_k: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
):
    """Generate layouts through the RALF public interface.

    Args:
        images: Poster/content images. When omitted, the pipeline uses a
            zero image for smoke/debug calls; converted checkpoints were
            trained with real content inputs.
        saliency: Optional saliency maps.
        batch_size: Batch size when images are absent.
        seed: Convenience seed used only when `generator` is absent.
        generator: PyTorch generator; takes precedence over `seed`.
        condition_type: Canonical condition type or alias.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Optional requested element counts.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size for pixel boxes.
        retrieved_layouts: Explicit retrieved layouts. When no retrieval data is
            supplied, the model receives zero retrieval memory for smoke/debug
            calls rather than paper-equivalent retrieved examples.
        retrieved_images: Explicit retrieved images.
        retrieved_saliency: Explicit retrieved saliency maps.
        retrieved_indexes: Explicit retrieved indexes.
        retrieval: Canonical v2 retrieval container.
        retrieval_table: Optional model-side retrieval table.
        query_ids: Query ids used for table lookup when explicit examples are absent.
        relations: Optional relation constraints.
        num_inference_steps: Reserved v1 argument.
        output_type: `dataclass` or `dict`.
        return_intermediates: Whether to return retrieval debug metadata.
        temperature: Sampling temperature.
        top_k: Optional top-k sampling limit.

    Returns:
        LayoutGenerationOutput or dictionary.
    """
    _ = (num_elements, num_inference_steps)
    condition = normalize_condition_type(condition_type)
    if condition not in SUPPORTED_GENERATION_CONDITIONS:
        raise NotImplementedError(
            "This RALF port currently supports unconditional, label, "
            "label_size, completion, refinement, relation, retrieval, and "
            "content_image; "
            f"got {condition}"
        )

    encoded = self.processor(
        images=images,
        saliency=saliency,
        condition_type=condition,
        labels=labels,
        bbox=bbox,
        mask=mask,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas_size,
        retrieved_layouts=retrieved_layouts,
        retrieved_images=retrieved_images,
        retrieved_saliency=retrieved_saliency,
        retrieved_indexes=retrieved_indexes,
        retrieval=retrieval,
        batch_size=batch_size,
    )
    model_device = next(self.model.parameters()).device
    generation_generator = self.prepare_generator(
        generator=generator,
        seed=seed,
        device=model_device,
    )
    intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]] = {}
    if "retrieval" in encoded:
        retrieval_batch = encoded["retrieval"]
        if retrieval_batch.indexes is not None:
            intermediates["retrieval"] = {"indexes": retrieval_batch.indexes}
    elif retrieval_table is not None and query_ids is not None:
        intermediates["retrieval"] = {"indexes": retrieval_table.lookup(query_ids)}
    sequences = self.model._generate_sequences(
        encoded["input_ids"].to(model_device),
        pixel_values=encoded["pixel_values"].to(model_device),
        saliency=encoded["saliency"].to(model_device),
        attention_mask=encoded["attention_mask"].to(model_device),
        max_length=self.config.max_token_length,
        temperature=temperature,
        top_k=top_k,
        generator=generation_generator,
        token_mask=self.processor.layout_tokenizer.token_mask(model_device),
        retrieved=encoded.get("retrieval"),
        condition_type=cast(RalfConfigTaskName, str(condition)),
        constraint_input_ids=encoded["input_ids"].to(model_device),
        constraint_mask=encoded["attention_mask"].to(model_device),
        constraint_element_mask=encoded["constraint_mask"].to(model_device),
        relationship_table=relations,
        sample_ids=query_ids,
    )
    return self.processor.post_process_layouts(
        sequences.cpu(),
        output_type=output_type,
        intermediates=intermediates if return_intermediates else None,
    )

RalfProcessor

Bases: ProcessorMixin

Assemble RALF model inputs and decode generated layouts.

Parameters:

Name Type Description Default
image_processor RalfImageProcessor

Image/saliency processor.

required
layout_tokenizer RalfLayoutTokenizer

Numeric layout tokenizer.

required

Examples:

>>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=2))
>>> encoded = processor(batch_size=1, condition_type="unconditional")
>>> "input_ids" in encoded
True
Source code in models/ralf/src/ralf/processing_ralf.py
 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
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
455
456
457
class RalfProcessor(ProcessorMixin):
    """Assemble RALF model inputs and decode generated layouts.

    Args:
        image_processor: Image/saliency processor.
        layout_tokenizer: Numeric layout tokenizer.

    Examples:
        >>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=2))
        >>> encoded = processor(batch_size=1, condition_type="unconditional")
        >>> "input_ids" in encoded
        True
    """

    attributes = ["image_processor", "layout_tokenizer"]
    image_processor_class = "RalfImageProcessor"
    tokenizer_class = "RalfLayoutTokenizer"

    def __init__(
        self,
        image_processor: RalfImageProcessor,
        layout_tokenizer: RalfLayoutTokenizer,
    ) -> None:
        """Initialize processor components."""
        self.image_processor = image_processor
        self.layout_tokenizer = layout_tokenizer
        super().__init__(image_processor, layout_tokenizer)

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        push_to_hub: bool = False,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Save local RALF processor components.

        Args:
            save_directory: Directory to write processor files.
            push_to_hub: Accepted for `ProcessorMixin` compatibility; ignored.
            kwargs: Accepted for `ProcessorMixin` compatibility; ignored.

        Examples:
            >>> import tempfile
            >>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=1))
            >>> with tempfile.TemporaryDirectory() as path:
            ...     processor.save_pretrained(path)
            ...     bool((Path(path) / "processor_config.json").exists())
            True
        """
        _ = (push_to_hub, kwargs)
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        self.image_processor.save_pretrained(root)
        self.layout_tokenizer.save_pretrained(root)
        (root / "processor_config.json").write_text(
            json.dumps(
                {
                    "processor_class": self.__class__.__name__,
                    "image_processor_class": self.image_processor.__class__.__name__,
                    "layout_tokenizer_class": self.layout_tokenizer.__class__.__name__,
                },
                indent=2,
                sort_keys=True,
            )
        )

    @classmethod
    def from_pretrained(
        cls,
        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",
        *,
        subfolder: str | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> "RalfProcessor":
        """Load local RALF processor components without Auto registration."""
        _ = (cache_dir, force_download, token, revision, kwargs)
        root = Path(pretrained_model_name_or_path)
        if subfolder is not None:
            root = root / subfolder
        config = RalfConfig.from_pretrained(root, local_files_only=local_files_only)
        return cls(
            image_processor=RalfImageProcessor.from_pretrained(root),
            layout_tokenizer=RalfLayoutTokenizer.from_pretrained(
                root,
                config=config,
                local_files_only=local_files_only,
            ),
        )

    @classmethod
    def _load_image_processor_from_pretrained(
        cls,
        sub_processor_type: str,
        pretrained_model_name_or_path: str | PathLike[str],
        subfolder: str = "",
        **kwargs: str | int | float | bool | None,
    ) -> RalfImageProcessor:
        """Load the local image processor for `ProcessorMixin.from_pretrained`."""
        _ = (sub_processor_type, kwargs)
        path = Path(pretrained_model_name_or_path)
        root = path / subfolder if subfolder else path
        return RalfImageProcessor.from_pretrained(root)

    @classmethod
    def _load_layout_tokenizer_from_pretrained(
        cls,
        sub_processor_type: str,
        pretrained_model_name_or_path: str | PathLike[str],
        subfolder: str = "",
        **kwargs: str | int | float | bool | None,
    ) -> RalfLayoutTokenizer:
        """Load the local layout tokenizer for `ProcessorMixin.from_pretrained`."""
        _ = sub_processor_type
        path = Path(pretrained_model_name_or_path)
        root = path / subfolder if subfolder else path
        return RalfLayoutTokenizer.from_pretrained(
            root,
            local_files_only=bool(kwargs.get("local_files_only", False)),
        )

    @classmethod
    def from_config(cls, config: RalfConfig) -> "RalfProcessor":
        """Create processor components from a config."""
        return cls(
            image_processor=RalfImageProcessor(
                cast(tuple[int, int] | None, config.image_size)
            ),
            layout_tokenizer=RalfLayoutTokenizer(config),
        )

    @property
    def config(self) -> RalfConfig:
        """Return tokenizer-backed RALF config."""
        return self.layout_tokenizer.config

    def normalize_condition_type(
        self, condition_type: ConditionType | str
    ) -> ConditionType:
        """Normalize a public condition string."""
        return normalize_condition_type(condition_type)

    def _coerce_labels(
        self,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None,
        batch_size: int,
    ) -> Int[torch.Tensor, "batch elements"]:
        if labels is None:
            return torch.zeros((batch_size, 0), dtype=torch.long)
        if isinstance(labels, torch.Tensor):
            tensor = labels.long()
            return tensor.unsqueeze(0) if tensor.ndim == 1 else tensor
        labels_list = list(labels)
        if not labels_list:
            return torch.zeros((batch_size, 0), dtype=torch.long)
        first = labels_list[0]
        rows = (
            labels_list
            if isinstance(first, Sequence) and not isinstance(first, str)
            else [labels_list]
        )
        label2id = cast(dict[str, int], self.config.label2id)
        out = []
        typed_rows = cast(list[Sequence[int | str]], rows)
        for row in typed_rows:
            values = []
            for item in row:
                if isinstance(item, str):
                    values.append(label2id[item.lower()])
                else:
                    values.append(int(item))
            out.append(values)
        return torch.tensor(out, dtype=torch.long)

    def _coerce_bbox(
        self,
        bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None,
        *,
        labels: Int[torch.Tensor, "batch elements"],
        box_format: BoxFormat | str,
        normalized: bool,
        canvas_size: tuple[int, int] | None,
    ) -> Float[torch.Tensor, "batch elements 4"]:
        if bbox is None:
            return torch.zeros((labels.size(0), labels.size(1), 4), dtype=torch.float32)
        tensor = torch.as_tensor(bbox, dtype=torch.float32)
        if tensor.ndim == 2:
            tensor = tensor.unsqueeze(0)
        if not normalized:
            if canvas_size is None:
                raise ValueError("canvas_size is required when normalized=False")

            return normalize_boxes(
                tensor, canvas_size=canvas_size, box_format=box_format
            )
        fmt = normalize_box_format(box_format)
        if fmt is BoxFormat.xywh:
            return tensor.clamp(0.0, 1.0)
        if fmt is BoxFormat.ltwh:
            from laygen.common.bbox import ltwh_to_xywh

            return ltwh_to_xywh(tensor).clamp(0.0, 1.0)
        from laygen.common.bbox import ltrb_to_xywh

        return ltrb_to_xywh(tensor).clamp(0.0, 1.0)

    def __call__(
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        saliency: ImageInput | Sequence[ImageInput] | None = None,
        condition_type: ConditionType | str = ConditionType.unconditional,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[bool]
        | Sequence[Sequence[bool]]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        retrieved_layouts: Mapping[
            str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
        ]
        | None = None,
        retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
        retrieved_saliency: RalfSequenceInput
        | Shaped[torch.Tensor, "..."]
        | None = None,
        retrieved_indexes: Int[torch.Tensor, "batch candidates"]
        | Sequence[Sequence[int]]
        | None = None,
        retrieval: Mapping[
            str,
            RalfRetrievalValue
            | Shaped[torch.Tensor, "..."]
            | Mapping[str, Shaped[torch.Tensor, "..."]],
        ]
        | None = None,
        relations: Mapping[str, RalfRetrievalValue] | None = None,
        batch_size: int = 1,
        return_tensors: RalfReturnTensor = "pt",
    ) -> BatchEncoding:
        """Encode public RALF inputs into tensors.

        Args:
            images: Poster/content image inputs.
            saliency: Optional saliency maps.
            condition_type: Canonical condition type or alias.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Optional requested element counts.
            box_format: Input box format.
            normalized: Whether `bbox` is already normalized.
            canvas_size: Pixel canvas size for unnormalized boxes.
            retrieved_layouts: Explicit retrieved layouts.
            retrieved_images: Explicit retrieved images.
            retrieved_saliency: Explicit retrieved saliency maps.
            retrieved_indexes: Explicit retrieved cache indexes.
            retrieval: Canonical v2 retrieval container.
            relations: Optional relation constraints.
            batch_size: Batch size used when no labels/images are supplied.
            return_tensors: Tensor format; only `pt` is supported.

        Returns:
            BatchEncoding containing model inputs.
        """
        _ = (num_elements, relations)
        condition = normalize_condition_type(condition_type)
        image_batch = self.image_processor.preprocess(
            images, saliency, return_tensors=return_tensors
        )
        batch_size = (
            int(image_batch["pixel_values"].size(0))
            if images is not None
            else batch_size
        )
        label_tensor = self._coerce_labels(labels, batch_size)
        bbox_tensor = self._coerce_bbox(
            bbox,
            labels=label_tensor,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        if mask is None:
            mask_tensor = torch.ones(label_tensor.shape, dtype=torch.bool)
        else:
            mask_tensor = torch.as_tensor(mask, dtype=torch.bool)
            if mask_tensor.ndim == 1:
                mask_tensor = mask_tensor.unsqueeze(0)
        tokenized = self.layout_tokenizer.encode_layout(
            labels=label_tensor,
            bbox=bbox_tensor,
            mask=mask_tensor,
        )
        output = BatchEncoding(
            {
                **image_batch,
                **tokenized,
                "condition_type": condition,
                "constraint_labels": label_tensor,
                "constraint_bbox": bbox_tensor,
                "constraint_mask": mask_tensor,
            }
        )
        retrieval_payload = retrieval or {}
        explicit_layouts = (
            retrieved_layouts
            or retrieval_payload.get("items")
            or retrieval_payload.get("examples")
        )
        if explicit_layouts is not None:
            output["retrieval"] = self._build_retrieval_batch(
                cast(
                    Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]]
                    | RalfSequenceInput
                    | Shaped[torch.Tensor, "..."],
                    explicit_layouts,
                ),
                cast(
                    Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                    retrieved_images
                    if retrieved_images is not None
                    else retrieval_payload.get("images"),
                ),
                cast(
                    Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                    retrieved_saliency
                    if retrieved_saliency is not None
                    else retrieval_payload.get("saliency"),
                ),
                cast(
                    Int[torch.Tensor, "batch candidates"]
                    | Sequence[Sequence[int]]
                    | None,
                    retrieved_indexes
                    if retrieved_indexes is not None
                    else retrieval_payload.get("ids"),
                ),
            )
        return output

    def _build_retrieval_batch(
        self,
        layouts: Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]]
        | RalfSequenceInput
        | Shaped[torch.Tensor, "..."],
        images: Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
        saliency: Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
        indexes: Int[torch.Tensor, "batch candidates"] | Sequence[Sequence[int]] | None,
    ) -> RalfRetrievedBatch:
        data = cast(
            Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]],
            layouts if isinstance(layouts, Mapping) else {"bbox": layouts},
        )
        bbox = torch.as_tensor(data["bbox"], dtype=torch.float32)
        labels = torch.as_tensor(
            data.get("labels", torch.zeros(bbox.shape[:-1])), dtype=torch.long
        )
        mask = torch.as_tensor(
            data.get("mask", torch.ones(labels.shape)), dtype=torch.bool
        )
        batch, candidates = bbox.shape[:2]
        image_tensor = torch.zeros(batch, candidates, 3, 1, 1)
        saliency_tensor = torch.zeros(batch, candidates, 1, 1, 1)
        if images is not None:
            image_tensor = torch.as_tensor(images, dtype=torch.float32)
        if saliency is not None:
            saliency_tensor = torch.as_tensor(saliency, dtype=torch.float32)
        index_tensor = (
            None if indexes is None else torch.as_tensor(indexes, dtype=torch.long)
        )
        return RalfRetrievedBatch(
            image=image_tensor,
            saliency=saliency_tensor,
            bbox=bbox,
            labels=labels,
            mask=mask,
            indexes=index_tensor,
        )

    def post_process_layouts(
        self,
        sequences: Int[torch.Tensor, "batch tokens"],
        *,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]]
        | None = None,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Shaped[torch.Tensor, "..."]
            | dict[int, str]
            | Mapping[str, Shaped[torch.Tensor, "..."]]
            | None,
        ]
    ):
        """Decode generated token ids to the common output schema."""
        decoded = self.layout_tokenizer.decode_layout(sequences.cpu())
        output = LayoutGenerationOutput(
            bbox=decoded["bbox"],
            labels=decoded["labels"],
            mask=decoded["mask"],
            id2label=cast(dict[int, str], self.config.id2label),
            sequences=sequences.cpu(),
            intermediates=intermediates,
        )
        if output_type == "dict":
            return dict(output.items())
        return output

config property

config: RalfConfig

Return tokenizer-backed RALF config.

__init__

__init__(
    image_processor: RalfImageProcessor,
    layout_tokenizer: RalfLayoutTokenizer,
) -> None

Initialize processor components.

Source code in models/ralf/src/ralf/processing_ralf.py
52
53
54
55
56
57
58
59
60
def __init__(
    self,
    image_processor: RalfImageProcessor,
    layout_tokenizer: RalfLayoutTokenizer,
) -> None:
    """Initialize processor components."""
    self.image_processor = image_processor
    self.layout_tokenizer = layout_tokenizer
    super().__init__(image_processor, layout_tokenizer)

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None

Save local RALF processor components.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Directory to write processor files.

required
push_to_hub bool

Accepted for ProcessorMixin compatibility; ignored.

False
kwargs str | int | float | bool | None

Accepted for ProcessorMixin compatibility; ignored.

{}

Examples:

>>> import tempfile
>>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=1))
>>> with tempfile.TemporaryDirectory() as path:
...     processor.save_pretrained(path)
...     bool((Path(path) / "processor_config.json").exists())
True
Source code in models/ralf/src/ralf/processing_ralf.py
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
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Save local RALF processor components.

    Args:
        save_directory: Directory to write processor files.
        push_to_hub: Accepted for `ProcessorMixin` compatibility; ignored.
        kwargs: Accepted for `ProcessorMixin` compatibility; ignored.

    Examples:
        >>> import tempfile
        >>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=1))
        >>> with tempfile.TemporaryDirectory() as path:
        ...     processor.save_pretrained(path)
        ...     bool((Path(path) / "processor_config.json").exists())
        True
    """
    _ = (push_to_hub, kwargs)
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    self.image_processor.save_pretrained(root)
    self.layout_tokenizer.save_pretrained(root)
    (root / "processor_config.json").write_text(
        json.dumps(
            {
                "processor_class": self.__class__.__name__,
                "image_processor_class": self.image_processor.__class__.__name__,
                "layout_tokenizer_class": self.layout_tokenizer.__class__.__name__,
            },
            indent=2,
            sort_keys=True,
        )
    )

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",
    *,
    subfolder: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> "RalfProcessor"

Load local RALF processor components without Auto registration.

Source code in models/ralf/src/ralf/processing_ralf.py
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
@classmethod
def from_pretrained(
    cls,
    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",
    *,
    subfolder: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> "RalfProcessor":
    """Load local RALF processor components without Auto registration."""
    _ = (cache_dir, force_download, token, revision, kwargs)
    root = Path(pretrained_model_name_or_path)
    if subfolder is not None:
        root = root / subfolder
    config = RalfConfig.from_pretrained(root, local_files_only=local_files_only)
    return cls(
        image_processor=RalfImageProcessor.from_pretrained(root),
        layout_tokenizer=RalfLayoutTokenizer.from_pretrained(
            root,
            config=config,
            local_files_only=local_files_only,
        ),
    )

from_config classmethod

from_config(config: RalfConfig) -> 'RalfProcessor'

Create processor components from a config.

Source code in models/ralf/src/ralf/processing_ralf.py
159
160
161
162
163
164
165
166
167
@classmethod
def from_config(cls, config: RalfConfig) -> "RalfProcessor":
    """Create processor components from a config."""
    return cls(
        image_processor=RalfImageProcessor(
            cast(tuple[int, int] | None, config.image_size)
        ),
        layout_tokenizer=RalfLayoutTokenizer(config),
    )

normalize_condition_type

normalize_condition_type(
    condition_type: ConditionType | str,
) -> ConditionType

Normalize a public condition string.

Source code in models/ralf/src/ralf/processing_ralf.py
174
175
176
177
178
def normalize_condition_type(
    self, condition_type: ConditionType | str
) -> ConditionType:
    """Normalize a public condition string."""
    return normalize_condition_type(condition_type)

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput
    | Sequence[ImageInput]
    | None = None,
    condition_type: ConditionType
    | str = ConditionType.unconditional,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | RalfSequenceInput
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[Tensor, "..."]
        | Mapping[str, Shaped[Tensor, "..."]],
    ]
    | None = None,
    relations: Mapping[str, RalfRetrievalValue]
    | None = None,
    batch_size: int = 1,
    return_tensors: RalfReturnTensor = "pt",
) -> BatchEncoding

Encode public RALF inputs into tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster/content image inputs.

None
saliency ImageInput | Sequence[ImageInput] | None

Optional saliency maps.

None
condition_type ConditionType | str

Canonical condition type or alias.

unconditional
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | RalfSequenceInput | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[bool] | Sequence[Sequence[bool]] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element counts.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether bbox is already normalized.

True
canvas_size tuple[int, int] | None

Pixel canvas size for unnormalized boxes.

None
retrieved_layouts Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...']] | None

Explicit retrieved layouts.

None
retrieved_images RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved images.

None
retrieved_saliency RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved saliency maps.

None
retrieved_indexes Int[Tensor, 'batch candidates'] | Sequence[Sequence[int]] | None

Explicit retrieved cache indexes.

None
retrieval Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...'] | Mapping[str, Shaped[Tensor, '...']]] | None

Canonical v2 retrieval container.

None
relations Mapping[str, RalfRetrievalValue] | None

Optional relation constraints.

None
batch_size int

Batch size used when no labels/images are supplied.

1
return_tensors RalfReturnTensor

Tensor format; only pt is supported.

'pt'

Returns:

Type Description
BatchEncoding

BatchEncoding containing model inputs.

Source code in models/ralf/src/ralf/processing_ralf.py
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
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
def __call__(
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput | Sequence[ImageInput] | None = None,
    condition_type: ConditionType | str = ConditionType.unconditional,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[torch.Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[torch.Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[torch.Tensor, "..."]
        | Mapping[str, Shaped[torch.Tensor, "..."]],
    ]
    | None = None,
    relations: Mapping[str, RalfRetrievalValue] | None = None,
    batch_size: int = 1,
    return_tensors: RalfReturnTensor = "pt",
) -> BatchEncoding:
    """Encode public RALF inputs into tensors.

    Args:
        images: Poster/content image inputs.
        saliency: Optional saliency maps.
        condition_type: Canonical condition type or alias.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Optional requested element counts.
        box_format: Input box format.
        normalized: Whether `bbox` is already normalized.
        canvas_size: Pixel canvas size for unnormalized boxes.
        retrieved_layouts: Explicit retrieved layouts.
        retrieved_images: Explicit retrieved images.
        retrieved_saliency: Explicit retrieved saliency maps.
        retrieved_indexes: Explicit retrieved cache indexes.
        retrieval: Canonical v2 retrieval container.
        relations: Optional relation constraints.
        batch_size: Batch size used when no labels/images are supplied.
        return_tensors: Tensor format; only `pt` is supported.

    Returns:
        BatchEncoding containing model inputs.
    """
    _ = (num_elements, relations)
    condition = normalize_condition_type(condition_type)
    image_batch = self.image_processor.preprocess(
        images, saliency, return_tensors=return_tensors
    )
    batch_size = (
        int(image_batch["pixel_values"].size(0))
        if images is not None
        else batch_size
    )
    label_tensor = self._coerce_labels(labels, batch_size)
    bbox_tensor = self._coerce_bbox(
        bbox,
        labels=label_tensor,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas_size,
    )
    if mask is None:
        mask_tensor = torch.ones(label_tensor.shape, dtype=torch.bool)
    else:
        mask_tensor = torch.as_tensor(mask, dtype=torch.bool)
        if mask_tensor.ndim == 1:
            mask_tensor = mask_tensor.unsqueeze(0)
    tokenized = self.layout_tokenizer.encode_layout(
        labels=label_tensor,
        bbox=bbox_tensor,
        mask=mask_tensor,
    )
    output = BatchEncoding(
        {
            **image_batch,
            **tokenized,
            "condition_type": condition,
            "constraint_labels": label_tensor,
            "constraint_bbox": bbox_tensor,
            "constraint_mask": mask_tensor,
        }
    )
    retrieval_payload = retrieval or {}
    explicit_layouts = (
        retrieved_layouts
        or retrieval_payload.get("items")
        or retrieval_payload.get("examples")
    )
    if explicit_layouts is not None:
        output["retrieval"] = self._build_retrieval_batch(
            cast(
                Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]]
                | RalfSequenceInput
                | Shaped[torch.Tensor, "..."],
                explicit_layouts,
            ),
            cast(
                Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                retrieved_images
                if retrieved_images is not None
                else retrieval_payload.get("images"),
            ),
            cast(
                Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                retrieved_saliency
                if retrieved_saliency is not None
                else retrieval_payload.get("saliency"),
            ),
            cast(
                Int[torch.Tensor, "batch candidates"]
                | Sequence[Sequence[int]]
                | None,
                retrieved_indexes
                if retrieved_indexes is not None
                else retrieval_payload.get("ids"),
            ),
        )
    return output

post_process_layouts

post_process_layouts(
    sequences: Int[Tensor, "batch tokens"],
    *,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    intermediates: dict[
        str, Mapping[str, Shaped[Tensor, "..."] | str]
    ]
    | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
)

Decode generated token ids to the common output schema.

Source code in models/ralf/src/ralf/processing_ralf.py
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
455
456
457
def post_process_layouts(
    self,
    sequences: Int[torch.Tensor, "batch tokens"],
    *,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]]
    | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
):
    """Decode generated token ids to the common output schema."""
    decoded = self.layout_tokenizer.decode_layout(sequences.cpu())
    output = LayoutGenerationOutput(
        bbox=decoded["bbox"],
        labels=decoded["labels"],
        mask=decoded["mask"],
        id2label=cast(dict[int, str], self.config.id2label),
        sequences=sequences.cpu(),
        intermediates=intermediates,
    )
    if output_type == "dict":
        return dict(output.items())
    return output

RalfRetrievalTable

Lookup table from query ids to retrieved training indexes.

Parameters:

Name Type Description Default
table Mapping[int | str, Sequence[int]]

Mapping from query ids to ordered retrieved ids.

required
top_k int

Number of retrieved ids returned per query.

required

Examples:

>>> table = RalfRetrievalTable({"a": [3, 4, 5]}, top_k=2)
>>> table.lookup(["a"]).tolist()
[[3, 4]]
Source code in models/ralf/src/ralf/retrieval.py
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
class RalfRetrievalTable:
    """Lookup table from query ids to retrieved training indexes.

    Args:
        table: Mapping from query ids to ordered retrieved ids.
        top_k: Number of retrieved ids returned per query.

    Examples:
        >>> table = RalfRetrievalTable({"a": [3, 4, 5]}, top_k=2)
        >>> table.lookup(["a"]).tolist()
        [[3, 4]]
    """

    def __init__(self, table: Mapping[int | str, Sequence[int]], top_k: int) -> None:
        """Initialize lookup table."""
        self.table = {
            str(key): [int(value) for value in values] for key, values in table.items()
        }
        self.top_k = int(top_k)

    @classmethod
    def from_pretrained(
        cls, path: str | Path, top_k: int | None = None
    ) -> "RalfRetrievalTable":
        """Load `retrieval_table.json` from a checkpoint directory."""
        root = Path(path)
        with (root / "retrieval_table.json").open() as f:
            payload = json.load(f)
        return cls(payload["table"], top_k=top_k or int(payload["top_k"]))

    def save_pretrained(self, save_directory: str | Path) -> tuple[str]:
        """Save the table next to converted checkpoint metadata."""
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        path = root / "retrieval_table.json"
        with path.open("w") as f:
            json.dump(
                {"top_k": self.top_k, "table": self.table}, f, indent=2, sort_keys=True
            )
        return (str(path),)

    def lookup(self, ids: Sequence[int | str]) -> Int[torch.Tensor, "batch candidates"]:
        """Return retrieved indexes for query ids."""
        rows = []
        for item in ids:
            values = self.table[str(item)][: self.top_k]
            if len(values) < self.top_k:
                values = values + [-1] * (self.top_k - len(values))
            rows.append(values)
        return torch.tensor(rows, dtype=torch.long)

__init__

__init__(
    table: Mapping[int | str, Sequence[int]], top_k: int
) -> None

Initialize lookup table.

Source code in models/ralf/src/ralf/retrieval.py
48
49
50
51
52
53
def __init__(self, table: Mapping[int | str, Sequence[int]], top_k: int) -> None:
    """Initialize lookup table."""
    self.table = {
        str(key): [int(value) for value in values] for key, values in table.items()
    }
    self.top_k = int(top_k)

from_pretrained classmethod

from_pretrained(
    path: str | Path, top_k: int | None = None
) -> "RalfRetrievalTable"

Load retrieval_table.json from a checkpoint directory.

Source code in models/ralf/src/ralf/retrieval.py
55
56
57
58
59
60
61
62
63
@classmethod
def from_pretrained(
    cls, path: str | Path, top_k: int | None = None
) -> "RalfRetrievalTable":
    """Load `retrieval_table.json` from a checkpoint directory."""
    root = Path(path)
    with (root / "retrieval_table.json").open() as f:
        payload = json.load(f)
    return cls(payload["table"], top_k=top_k or int(payload["top_k"]))

save_pretrained

save_pretrained(save_directory: str | Path) -> tuple[str]

Save the table next to converted checkpoint metadata.

Source code in models/ralf/src/ralf/retrieval.py
65
66
67
68
69
70
71
72
73
74
def save_pretrained(self, save_directory: str | Path) -> tuple[str]:
    """Save the table next to converted checkpoint metadata."""
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    path = root / "retrieval_table.json"
    with path.open("w") as f:
        json.dump(
            {"top_k": self.top_k, "table": self.table}, f, indent=2, sort_keys=True
        )
    return (str(path),)

lookup

lookup(
    ids: Sequence[int | str],
) -> Int[torch.Tensor, "batch candidates"]

Return retrieved indexes for query ids.

Source code in models/ralf/src/ralf/retrieval.py
76
77
78
79
80
81
82
83
84
def lookup(self, ids: Sequence[int | str]) -> Int[torch.Tensor, "batch candidates"]:
    """Return retrieved indexes for query ids."""
    rows = []
    for item in ids:
        values = self.table[str(item)][: self.top_k]
        if len(values) < self.top_k:
            values = values + [-1] * (self.top_k - len(values))
        rows.append(values)
    return torch.tensor(rows, dtype=torch.long)

RalfRetrievedBatch dataclass

Batch of explicit retrieved examples for RALF.

Parameters:

Name Type Description Default
image Float[Tensor, 'batch candidates channels height width']

Retrieved RGB images with shape (batch, candidates, channels, height, width).

required
saliency Float[Tensor, 'batch candidates 1 height width']

Retrieved saliency maps with shape (batch, candidates, 1, height, width).

required
bbox Float[Tensor, 'batch candidates elements 4']

Retrieved normalized center xywh boxes.

required
labels Int[Tensor, 'batch candidates elements']

Retrieved dataset-local labels.

required
mask Bool[Tensor, 'batch candidates elements']

Retrieved valid-element masks.

required
indexes Int[Tensor, 'batch candidates'] | None

Optional selected cache indexes.

None
Source code in models/ralf/src/ralf/retrieval.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass
class RalfRetrievedBatch:
    """Batch of explicit retrieved examples for RALF.

    Args:
        image: Retrieved RGB images with shape `(batch, candidates, channels, height, width)`.
        saliency: Retrieved saliency maps with shape `(batch, candidates, 1, height, width)`.
        bbox: Retrieved normalized center `xywh` boxes.
        labels: Retrieved dataset-local labels.
        mask: Retrieved valid-element masks.
        indexes: Optional selected cache indexes.
    """

    image: Float[torch.Tensor, "batch candidates channels height width"]
    saliency: Float[torch.Tensor, "batch candidates 1 height width"]
    bbox: Float[torch.Tensor, "batch candidates elements 4"]
    labels: Int[torch.Tensor, "batch candidates elements"]
    mask: Bool[torch.Tensor, "batch candidates elements"]
    indexes: Int[torch.Tensor, "batch candidates"] | None = None

RalfLayoutTokenizer

Bases: PreTrainedTokenizer

PreTrainedTokenizer for RALF's numeric layout token sequences.

Parameters:

Name Type Description Default
config RalfConfig | None

RALF config that defines label and geometry vocabularies.

None
tokenizer_config_file str | None

Optional tokenizer metadata path loaded by from_pretrained.

None
kwargs str | int | float | bool | None

Standard PreTrainedTokenizer keyword arguments.

{}

Examples:

>>> tokenizer = RalfLayoutTokenizer(RalfConfig(max_seq_length=2))
>>> encoded = tokenizer.encode_layout(
...     labels=torch.tensor([[0]]),
...     bbox=torch.tensor([[[0.5, 0.5, 0.2, 0.2]]]),
...     mask=torch.tensor([[True]]),
... )
>>> encoded["input_ids"].shape[1] > 1
True
Source code in models/ralf/src/ralf/tokenization_ralf.py
 20
 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
 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
class RalfLayoutTokenizer(PreTrainedTokenizer):
    """PreTrainedTokenizer for RALF's numeric layout token sequences.

    Args:
        config: RALF config that defines label and geometry vocabularies.
        tokenizer_config_file: Optional tokenizer metadata path loaded by
            `from_pretrained`.
        kwargs: Standard `PreTrainedTokenizer` keyword arguments.

    Examples:
        >>> tokenizer = RalfLayoutTokenizer(RalfConfig(max_seq_length=2))
        >>> encoded = tokenizer.encode_layout(
        ...     labels=torch.tensor([[0]]),
        ...     bbox=torch.tensor([[[0.5, 0.5, 0.2, 0.2]]]),
        ...     mask=torch.tensor([[True]]),
        ... )
        >>> encoded["input_ids"].shape[1] > 1
        True
    """

    model_input_names = ["input_ids", "attention_mask"]
    vocab_files_names = {"tokenizer_config_file": TOKENIZER_CONFIG_FILE}

    def __init__(
        self,
        config: RalfConfig | None = None,
        tokenizer_config_file: str | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Initialize tokenizer metadata and synthetic token strings."""
        if config is None and tokenizer_config_file is not None:
            with Path(tokenizer_config_file).open() as f:
                config = RalfConfig(**json.load(f)["config"])
        if config is None:
            raise ValueError("RalfLayoutTokenizer requires an explicit config")

        self.config = config
        self._token2id = self._build_vocab()
        self._id2token = {idx: token for token, idx in self._token2id.items()}
        kwargs.setdefault("pad_token", "[pad]")
        kwargs.setdefault("bos_token", "[bos]")
        kwargs.setdefault("eos_token", "[eos]")
        kwargs.setdefault("unk_token", "[unk]")
        kwargs.setdefault("model_max_length", self.config.max_token_length + 1)
        kwargs.setdefault("clean_up_tokenization_spaces", False)
        super().__init__(
            **kwargs,
        )

    @property
    def vocab_size(self) -> int:
        """Return total vocabulary size."""
        return self.config.vocab_size

    def get_vocab(self) -> dict[str, int]:
        """Return synthetic token strings mapped to ids."""
        return dict(self._token2id)

    def _build_vocab(self) -> dict[str, int]:
        id2label = cast(dict[int, str], self.config.id2label)
        vocab = {f"label:{label}": int(idx) for idx, label in id2label.items()}
        for key in GEO_KEYS:
            start = self.config.bbox_token_offset(key)
            for idx in range(self.config.num_bin):
                vocab[f"{key}:{idx}"] = start + idx
        for token in self.config.special_tokens:
            vocab[f"[{token}]"] = self.config.special_token_id(token)
        return vocab

    def _tokenize(
        self, text: str, **kwargs: str | int | float | bool | None
    ) -> list[str]:
        _ = kwargs
        return text.strip().split()

    def _convert_token_to_id(self, token: str) -> int:
        return self._token2id.get(token, self.config.pad_token_id)

    def _convert_id_to_token(self, index: int) -> str:
        return self._id2token.get(int(index), "[unk]")

    def convert_tokens_to_string(self, tokens: list[str]) -> str:
        """Join synthetic layout tokens."""
        return " ".join(tokens)

    def save_vocabulary(
        self, save_directory: str, filename_prefix: str | None = None
    ) -> tuple[str, ...]:
        """Save tokenizer metadata for Hub-compatible loading."""
        out_dir = Path(save_directory)
        out_dir.mkdir(parents=True, exist_ok=True)
        name = (
            TOKENIZER_CONFIG_FILE
            if filename_prefix is None
            else f"{filename_prefix}-{TOKENIZER_CONFIG_FILE}"
        )
        path = out_dir / name
        with path.open("w") as f:
            json.dump({"config": self.config.to_dict()}, f, indent=2, sort_keys=True)
        return (str(path),)

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        legacy_format: bool | None = None,
        filename_prefix: str | None = None,
        push_to_hub: bool = False,
        **kwargs: str | int | float | bool | None,
    ) -> tuple[str, ...]:
        """Save tokenizer files and the paired `RalfConfig`.

        Args:
            save_directory: Output directory.
            legacy_format: Standard tokenizer save flag.
            filename_prefix: Optional filename prefix.
            push_to_hub: Whether to push through Hugging Face Hub helpers.
            kwargs: Reserved tokenizer save arguments.

        Returns:
            Written tokenizer file paths.
        """
        paths = super().save_pretrained(
            save_directory,
            legacy_format=legacy_format,
            filename_prefix=filename_prefix,
            push_to_hub=push_to_hub,
            **kwargs,
        )
        self.config.save_pretrained(save_directory)
        return paths

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str | PathLike[str],
        *inputs: str,
        config: RalfConfig | None = None,
        cache_dir: str | PathLike[str] | None = None,
        force_download: bool = False,
        local_files_only: bool = False,
        token: str | bool | None = None,
        revision: str = "main",
    ) -> "RalfLayoutTokenizer":
        """Load tokenizer metadata from a checkpoint directory."""
        if config is None:
            config = RalfConfig.from_pretrained(pretrained_model_name_or_path)
        loaded = super().from_pretrained(
            pretrained_model_name_or_path,
            *inputs,
            cache_dir=cache_dir,
            force_download=force_download,
            local_files_only=local_files_only,
            token=token,
            revision=revision,
            config=config,
        )
        return cast("RalfLayoutTokenizer", loaded)

    def _quantize(self, values: Float[torch.Tensor, "..."]) -> Int[torch.Tensor, "..."]:
        values = values.clamp(0.0, 1.0)
        boundaries = (
            torch.arange(
                1,
                self.config.num_bin + 1,
                device=values.device,
                dtype=values.dtype,
            )
            / self.config.num_bin
        )
        return torch.bucketize(values, boundaries).long()

    def _dequantize(self, ids: Int[torch.Tensor, "..."]) -> Float[torch.Tensor, "..."]:
        ids = ids.clamp(0, self.config.num_bin - 1)
        starts = ids.float() / self.config.num_bin
        return starts + (0.5 / self.config.num_bin)

    def encode_layout(
        self,
        *,
        labels: Int[torch.Tensor, "batch elements"],
        bbox: Float[torch.Tensor, "batch elements 4"],
        mask: Bool[torch.Tensor, "batch elements"] | None = None,
    ) -> BatchEncoding:
        """Encode public normalized center `xywh` layouts to RALF tokens.

        Args:
            labels: Dataset-local integer labels.
            bbox: Normalized center `xywh` boxes.
            mask: Valid-element mask. If omitted, every element is valid.

        Returns:
            BatchEncoding with `input_ids` and `attention_mask`.

        Raises:
            ValueError: If tensor ranks are invalid.
        """
        if labels.ndim != 2 or bbox.ndim != 3 or bbox.shape[-1] != 4:
            raise ValueError("labels must be (B,S) and bbox must be (B,S,4)")

        if mask is None:
            mask = torch.ones_like(labels, dtype=torch.bool)
        batch, elements = labels.shape
        max_elements = min(elements, self.config.max_seq_length)
        seq = labels.new_full(
            (batch, self.config.max_token_length),
            self.config.pad_token_id,
        )
        attention_mask = torch.zeros_like(seq, dtype=torch.bool)
        geometry = {
            "center_x": self._quantize(bbox[..., 0]),
            "center_y": self._quantize(bbox[..., 1]),
            "width": self._quantize(bbox[..., 2]),
            "height": self._quantize(bbox[..., 3]),
        }
        for element_idx in range(max_elements):
            for var_idx, key in enumerate(self.config.var_order):
                token_idx = element_idx * len(self.config.var_order) + var_idx
                valid = mask[:, element_idx]
                if key == "label":
                    values = labels[:, element_idx].clamp(0, self.config.num_labels - 1)
                else:
                    values = geometry[key][
                        :, element_idx
                    ] + self.config.bbox_token_offset(key)
                seq[:, token_idx] = torch.where(valid, values, seq[:, token_idx])
                attention_mask[:, token_idx] = valid
        lengths = mask[:, :max_elements].sum(dim=1) * len(self.config.var_order)
        for batch_idx, length in enumerate(lengths.tolist()):
            if length < seq.size(1):
                seq[batch_idx, length] = self.config.eos_token_id
                attention_mask[batch_idx, length] = True
        bos = labels.new_full((batch, 1), self.config.bos_token_id)
        bos_mask = torch.ones((batch, 1), dtype=torch.bool, device=labels.device)
        return BatchEncoding(
            {
                "input_ids": torch.cat([bos, seq], dim=1),
                "attention_mask": torch.cat([bos_mask, attention_mask], dim=1),
            }
        )

    def decode_layout(
        self, sequences: Int[torch.Tensor, "batch tokens"]
    ) -> dict[str, Shaped[torch.Tensor, "..."]]:
        """Decode RALF token ids to normalized layout tensors.

        Args:
            sequences: Generated token ids, with or without a leading BOS.

        Returns:
            Dictionary containing `bbox`, `labels`, and `mask`.
        """
        if sequences.ndim != 2:
            raise ValueError("sequences must have shape (B,T)")

        if sequences.size(1) and torch.all(sequences[:, 0] == self.config.bos_token_id):
            sequences = sequences[:, 1:]
        usable = sequences[:, : self.config.max_token_length]
        batch = usable.size(0)
        padded = usable.new_full(
            (batch, self.config.max_token_length),
            self.config.pad_token_id,
        )
        padded[:, : usable.size(1)] = usable
        tokens = padded.reshape(
            batch, self.config.max_seq_length, len(self.config.var_order)
        )
        labels = torch.zeros(
            (batch, self.config.max_seq_length),
            dtype=torch.long,
            device=sequences.device,
        )
        bbox_parts = {
            key: torch.zeros_like(labels, dtype=torch.float32) for key in GEO_KEYS
        }
        mask = torch.ones_like(labels, dtype=torch.bool)
        for var_idx, key in enumerate(self.config.var_order):
            values = tokens[..., var_idx]
            if key == "label":
                labels = values.clamp(0, self.config.num_labels - 1)
                mask &= values.lt(self.config.num_labels)
                eos_seen = torch.cumsum(values.eq(self.config.eos_token_id), dim=1) > 0
                mask &= ~eos_seen
            else:
                local = values - self.config.bbox_token_offset(key)
                mask &= (local >= 0) & (local < self.config.num_bin)
                bbox_parts[key] = self._dequantize(local)
        bbox = torch.stack(
            (
                bbox_parts["center_x"],
                bbox_parts["center_y"],
                bbox_parts["width"],
                bbox_parts["height"],
            ),
            dim=-1,
        ).clamp(0.0, 1.0)
        labels = torch.where(mask, labels, torch.zeros_like(labels))
        bbox = torch.where(mask.unsqueeze(-1), bbox, torch.zeros_like(bbox))
        return {"bbox": bbox, "labels": labels, "mask": mask}

    def token_mask(
        self, device: torch.device | None = None
    ) -> Bool[torch.Tensor, "tokens vocab"]:
        """Return valid-token masks by sequence position."""
        masks: list[Bool[torch.Tensor, "vocab"]] = []
        for _ in range(self.config.max_seq_length):
            for key in self.config.var_order:
                mask = torch.zeros(
                    self.config.vocab_size, dtype=torch.bool, device=device
                )
                if key == "label":
                    mask[: self.config.num_labels] = True
                    mask[self.config.eos_token_id] = True
                    mask[self.config.pad_token_id] = True
                else:
                    start = self.config.bbox_token_offset(key)
                    mask[start : start + self.config.num_bin] = True
                    mask[self.config.eos_token_id] = True
                    mask[self.config.pad_token_id] = True
                masks.append(mask)
        return torch.stack(masks, dim=0)

vocab_size property

vocab_size: int

Return total vocabulary size.

__init__

__init__(
    config: RalfConfig | None = None,
    tokenizer_config_file: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> None

Initialize tokenizer metadata and synthetic token strings.

Source code in models/ralf/src/ralf/tokenization_ralf.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
def __init__(
    self,
    config: RalfConfig | None = None,
    tokenizer_config_file: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Initialize tokenizer metadata and synthetic token strings."""
    if config is None and tokenizer_config_file is not None:
        with Path(tokenizer_config_file).open() as f:
            config = RalfConfig(**json.load(f)["config"])
    if config is None:
        raise ValueError("RalfLayoutTokenizer requires an explicit config")

    self.config = config
    self._token2id = self._build_vocab()
    self._id2token = {idx: token for token, idx in self._token2id.items()}
    kwargs.setdefault("pad_token", "[pad]")
    kwargs.setdefault("bos_token", "[bos]")
    kwargs.setdefault("eos_token", "[eos]")
    kwargs.setdefault("unk_token", "[unk]")
    kwargs.setdefault("model_max_length", self.config.max_token_length + 1)
    kwargs.setdefault("clean_up_tokenization_spaces", False)
    super().__init__(
        **kwargs,
    )

get_vocab

get_vocab() -> dict[str, int]

Return synthetic token strings mapped to ids.

Source code in models/ralf/src/ralf/tokenization_ralf.py
74
75
76
def get_vocab(self) -> dict[str, int]:
    """Return synthetic token strings mapped to ids."""
    return dict(self._token2id)

convert_tokens_to_string

convert_tokens_to_string(tokens: list[str]) -> str

Join synthetic layout tokens.

Source code in models/ralf/src/ralf/tokenization_ralf.py
101
102
103
def convert_tokens_to_string(self, tokens: list[str]) -> str:
    """Join synthetic layout tokens."""
    return " ".join(tokens)

save_vocabulary

save_vocabulary(
    save_directory: str, filename_prefix: str | None = None
) -> tuple[str, ...]

Save tokenizer metadata for Hub-compatible loading.

Source code in models/ralf/src/ralf/tokenization_ralf.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def save_vocabulary(
    self, save_directory: str, filename_prefix: str | None = None
) -> tuple[str, ...]:
    """Save tokenizer metadata for Hub-compatible loading."""
    out_dir = Path(save_directory)
    out_dir.mkdir(parents=True, exist_ok=True)
    name = (
        TOKENIZER_CONFIG_FILE
        if filename_prefix is None
        else f"{filename_prefix}-{TOKENIZER_CONFIG_FILE}"
    )
    path = out_dir / name
    with path.open("w") as f:
        json.dump({"config": self.config.to_dict()}, f, indent=2, sort_keys=True)
    return (str(path),)

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    legacy_format: bool | None = None,
    filename_prefix: str | None = None,
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> tuple[str, ...]

Save tokenizer files and the paired RalfConfig.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Output directory.

required
legacy_format bool | None

Standard tokenizer save flag.

None
filename_prefix str | None

Optional filename prefix.

None
push_to_hub bool

Whether to push through Hugging Face Hub helpers.

False
kwargs str | int | float | bool | None

Reserved tokenizer save arguments.

{}

Returns:

Type Description
tuple[str, ...]

Written tokenizer file paths.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    legacy_format: bool | None = None,
    filename_prefix: str | None = None,
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> tuple[str, ...]:
    """Save tokenizer files and the paired `RalfConfig`.

    Args:
        save_directory: Output directory.
        legacy_format: Standard tokenizer save flag.
        filename_prefix: Optional filename prefix.
        push_to_hub: Whether to push through Hugging Face Hub helpers.
        kwargs: Reserved tokenizer save arguments.

    Returns:
        Written tokenizer file paths.
    """
    paths = super().save_pretrained(
        save_directory,
        legacy_format=legacy_format,
        filename_prefix=filename_prefix,
        push_to_hub=push_to_hub,
        **kwargs,
    )
    self.config.save_pretrained(save_directory)
    return paths

from_pretrained classmethod

from_pretrained(
    pretrained_model_name_or_path: str | PathLike[str],
    *inputs: str,
    config: RalfConfig | None = None,
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
) -> "RalfLayoutTokenizer"

Load tokenizer metadata from a checkpoint directory.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str | PathLike[str],
    *inputs: str,
    config: RalfConfig | None = None,
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
) -> "RalfLayoutTokenizer":
    """Load tokenizer metadata from a checkpoint directory."""
    if config is None:
        config = RalfConfig.from_pretrained(pretrained_model_name_or_path)
    loaded = super().from_pretrained(
        pretrained_model_name_or_path,
        *inputs,
        cache_dir=cache_dir,
        force_download=force_download,
        local_files_only=local_files_only,
        token=token,
        revision=revision,
        config=config,
    )
    return cast("RalfLayoutTokenizer", loaded)

encode_layout

encode_layout(
    *,
    labels: Int[Tensor, "batch elements"],
    bbox: Float[Tensor, "batch elements 4"],
    mask: Bool[Tensor, "batch elements"] | None = None,
) -> BatchEncoding

Encode public normalized center xywh layouts to RALF tokens.

Parameters:

Name Type Description Default
labels Int[Tensor, 'batch elements']

Dataset-local integer labels.

required
bbox Float[Tensor, 'batch elements 4']

Normalized center xywh boxes.

required
mask Bool[Tensor, 'batch elements'] | None

Valid-element mask. If omitted, every element is valid.

None

Returns:

Type Description
BatchEncoding

BatchEncoding with input_ids and attention_mask.

Raises:

Type Description
ValueError

If tensor ranks are invalid.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
def encode_layout(
    self,
    *,
    labels: Int[torch.Tensor, "batch elements"],
    bbox: Float[torch.Tensor, "batch elements 4"],
    mask: Bool[torch.Tensor, "batch elements"] | None = None,
) -> BatchEncoding:
    """Encode public normalized center `xywh` layouts to RALF tokens.

    Args:
        labels: Dataset-local integer labels.
        bbox: Normalized center `xywh` boxes.
        mask: Valid-element mask. If omitted, every element is valid.

    Returns:
        BatchEncoding with `input_ids` and `attention_mask`.

    Raises:
        ValueError: If tensor ranks are invalid.
    """
    if labels.ndim != 2 or bbox.ndim != 3 or bbox.shape[-1] != 4:
        raise ValueError("labels must be (B,S) and bbox must be (B,S,4)")

    if mask is None:
        mask = torch.ones_like(labels, dtype=torch.bool)
    batch, elements = labels.shape
    max_elements = min(elements, self.config.max_seq_length)
    seq = labels.new_full(
        (batch, self.config.max_token_length),
        self.config.pad_token_id,
    )
    attention_mask = torch.zeros_like(seq, dtype=torch.bool)
    geometry = {
        "center_x": self._quantize(bbox[..., 0]),
        "center_y": self._quantize(bbox[..., 1]),
        "width": self._quantize(bbox[..., 2]),
        "height": self._quantize(bbox[..., 3]),
    }
    for element_idx in range(max_elements):
        for var_idx, key in enumerate(self.config.var_order):
            token_idx = element_idx * len(self.config.var_order) + var_idx
            valid = mask[:, element_idx]
            if key == "label":
                values = labels[:, element_idx].clamp(0, self.config.num_labels - 1)
            else:
                values = geometry[key][
                    :, element_idx
                ] + self.config.bbox_token_offset(key)
            seq[:, token_idx] = torch.where(valid, values, seq[:, token_idx])
            attention_mask[:, token_idx] = valid
    lengths = mask[:, :max_elements].sum(dim=1) * len(self.config.var_order)
    for batch_idx, length in enumerate(lengths.tolist()):
        if length < seq.size(1):
            seq[batch_idx, length] = self.config.eos_token_id
            attention_mask[batch_idx, length] = True
    bos = labels.new_full((batch, 1), self.config.bos_token_id)
    bos_mask = torch.ones((batch, 1), dtype=torch.bool, device=labels.device)
    return BatchEncoding(
        {
            "input_ids": torch.cat([bos, seq], dim=1),
            "attention_mask": torch.cat([bos_mask, attention_mask], dim=1),
        }
    )

decode_layout

decode_layout(
    sequences: Int[Tensor, "batch tokens"],
) -> dict[str, Shaped[torch.Tensor, "..."]]

Decode RALF token ids to normalized layout tensors.

Parameters:

Name Type Description Default
sequences Int[Tensor, 'batch tokens']

Generated token ids, with or without a leading BOS.

required

Returns:

Type Description
dict[str, Shaped[Tensor, '...']]

Dictionary containing bbox, labels, and mask.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
def decode_layout(
    self, sequences: Int[torch.Tensor, "batch tokens"]
) -> dict[str, Shaped[torch.Tensor, "..."]]:
    """Decode RALF token ids to normalized layout tensors.

    Args:
        sequences: Generated token ids, with or without a leading BOS.

    Returns:
        Dictionary containing `bbox`, `labels`, and `mask`.
    """
    if sequences.ndim != 2:
        raise ValueError("sequences must have shape (B,T)")

    if sequences.size(1) and torch.all(sequences[:, 0] == self.config.bos_token_id):
        sequences = sequences[:, 1:]
    usable = sequences[:, : self.config.max_token_length]
    batch = usable.size(0)
    padded = usable.new_full(
        (batch, self.config.max_token_length),
        self.config.pad_token_id,
    )
    padded[:, : usable.size(1)] = usable
    tokens = padded.reshape(
        batch, self.config.max_seq_length, len(self.config.var_order)
    )
    labels = torch.zeros(
        (batch, self.config.max_seq_length),
        dtype=torch.long,
        device=sequences.device,
    )
    bbox_parts = {
        key: torch.zeros_like(labels, dtype=torch.float32) for key in GEO_KEYS
    }
    mask = torch.ones_like(labels, dtype=torch.bool)
    for var_idx, key in enumerate(self.config.var_order):
        values = tokens[..., var_idx]
        if key == "label":
            labels = values.clamp(0, self.config.num_labels - 1)
            mask &= values.lt(self.config.num_labels)
            eos_seen = torch.cumsum(values.eq(self.config.eos_token_id), dim=1) > 0
            mask &= ~eos_seen
        else:
            local = values - self.config.bbox_token_offset(key)
            mask &= (local >= 0) & (local < self.config.num_bin)
            bbox_parts[key] = self._dequantize(local)
    bbox = torch.stack(
        (
            bbox_parts["center_x"],
            bbox_parts["center_y"],
            bbox_parts["width"],
            bbox_parts["height"],
        ),
        dim=-1,
    ).clamp(0.0, 1.0)
    labels = torch.where(mask, labels, torch.zeros_like(labels))
    bbox = torch.where(mask.unsqueeze(-1), bbox, torch.zeros_like(bbox))
    return {"bbox": bbox, "labels": labels, "mask": mask}

token_mask

token_mask(
    device: device | None = None,
) -> Bool[torch.Tensor, "tokens vocab"]

Return valid-token masks by sequence position.

Source code in models/ralf/src/ralf/tokenization_ralf.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def token_mask(
    self, device: torch.device | None = None
) -> Bool[torch.Tensor, "tokens vocab"]:
    """Return valid-token masks by sequence position."""
    masks: list[Bool[torch.Tensor, "vocab"]] = []
    for _ in range(self.config.max_seq_length):
        for key in self.config.var_order:
            mask = torch.zeros(
                self.config.vocab_size, dtype=torch.bool, device=device
            )
            if key == "label":
                mask[: self.config.num_labels] = True
                mask[self.config.eos_token_id] = True
                mask[self.config.pad_token_id] = True
            else:
                start = self.config.bbox_token_offset(key)
                mask[start : start + self.config.num_bin] = True
                mask[self.config.eos_token_id] = True
                mask[self.config.pad_token_id] = True
            masks.append(mask)
    return torch.stack(masks, dim=0)

configuration_ralf

Configuration for RALF checkpoints.

RalfConfig

Bases: PretrainedConfig

Configuration carrying RALF architecture and tokenizer metadata.

Parameters:

Name Type Description Default
dataset_name RalfDatasetName

Poster dataset key, usually cgl or pku_posterlayout.

'cgl'
task RalfConfigTaskName

Canonical condition type or checkpoint task alias.

'unconditional'
id2label Mapping[int | str, str] | None

Dataset-local label vocabulary persisted with the checkpoint.

None
max_seq_length int

Maximum number of layout elements.

10
num_bin int

Number of linear geometry bins per variable.

128
var_order Sequence[RalfLayoutVariable]

Token variable order.

DEFAULT_VAR_ORDER
special_tokens Sequence[str]

Special tokens stored after label and geometry tokens.

DEFAULT_SPECIAL_TOKENS
geo_quantization str

Geometry quantizer name. The converted package supports linear; conversion records other values for audit.

'linear'
is_loc_vocab_shared bool

Whether geometry variables share one token range.

False
d_model int

Image encoder hidden size.

256
decoder_d_model int

Decoder hidden size.

256
encoder_layers int

Number of image encoder transformer layers.

6
decoder_layers int

Number of decoder layers.

6
num_attention_heads int

Number of attention heads.

8
dropout float

Dropout probability.

0.1
retrieval_backbone str

Retrieval backbone name.

'dreamsim'
top_k int

Number of retrieved examples expected by the checkpoint.

16
use_reference_image bool

Whether retrieved reference images participate in fusion.

False
layout_backbone str

Layout encoder name.

'feature_extractor'
freeze_layout_encoder bool

Whether the layout encoder was frozen.

True
fusion str

Retrieval fusion variant.

'concat_cross_attention'
use_flag_embedding bool

Whether task flag embeddings are enabled.

True
use_multitask bool

Whether checkpoint was trained as multitask.

False
global_task_embedding bool

Whether global task embedding is enabled.

False
relation_size int

Maximum number of relation constraints.

10
image_channels int

Number of image channels consumed by the model.

4
image_size tuple[int, int] | list[int] | None

Optional (height, width) resize target.

None
sort_order Sequence[str]

Processor sort order metadata.

('label', 'lexicographic')
retrieval_metadata RalfConfigMetadata | None

Retrieval-cache metadata for conversion/parity.

None
original_config RalfConfigMetadata | None

Original config serialized as plain data.

None
kwargs str | int | float | bool | None

Extra PretrainedConfig keyword arguments.

{}
Source code in models/ralf/src/ralf/configuration_ralf.py
 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
class RalfConfig(PretrainedConfig):
    """Configuration carrying RALF architecture and tokenizer metadata.

    Args:
        dataset_name: Poster dataset key, usually `cgl` or `pku_posterlayout`.
        task: Canonical condition type or checkpoint task alias.
        id2label: Dataset-local label vocabulary persisted with the checkpoint.
        max_seq_length: Maximum number of layout elements.
        num_bin: Number of linear geometry bins per variable.
        var_order: Token variable order.
        special_tokens: Special tokens stored after label and geometry tokens.
        geo_quantization: Geometry quantizer name. The converted package supports
            `linear`; conversion records other values for audit.
        is_loc_vocab_shared: Whether geometry variables share one token range.
        d_model: Image encoder hidden size.
        decoder_d_model: Decoder hidden size.
        encoder_layers: Number of image encoder transformer layers.
        decoder_layers: Number of decoder layers.
        num_attention_heads: Number of attention heads.
        dropout: Dropout probability.
        retrieval_backbone: Retrieval backbone name.
        top_k: Number of retrieved examples expected by the checkpoint.
        use_reference_image: Whether retrieved reference images participate in fusion.
        layout_backbone: Layout encoder name.
        freeze_layout_encoder: Whether the layout encoder was frozen.
        fusion: Retrieval fusion variant.
        use_flag_embedding: Whether task flag embeddings are enabled.
        use_multitask: Whether checkpoint was trained as multitask.
        global_task_embedding: Whether global task embedding is enabled.
        relation_size: Maximum number of relation constraints.
        image_channels: Number of image channels consumed by the model.
        image_size: Optional `(height, width)` resize target.
        sort_order: Processor sort order metadata.
        retrieval_metadata: Retrieval-cache metadata for conversion/parity.
        original_config: Original config serialized as plain data.
        kwargs: Extra `PretrainedConfig` keyword arguments.
    """

    model_type = "ralf"

    def __init__(
        self,
        dataset_name: RalfDatasetName = "cgl",
        task: RalfConfigTaskName = "unconditional",
        id2label: Mapping[int | str, str] | None = None,
        max_seq_length: int = 10,
        num_bin: int = 128,
        var_order: Sequence[RalfLayoutVariable] = DEFAULT_VAR_ORDER,
        special_tokens: Sequence[str] = DEFAULT_SPECIAL_TOKENS,
        geo_quantization: str = "linear",
        is_loc_vocab_shared: bool = False,
        d_model: int = 256,
        decoder_d_model: int = 256,
        encoder_layers: int = 6,
        decoder_layers: int = 6,
        num_attention_heads: int = 8,
        dropout: float = 0.1,
        retrieval_backbone: str = "dreamsim",
        saliency_k: int | str = "None",
        top_k: int = 16,
        use_reference_image: bool = False,
        layout_backbone: str = "feature_extractor",
        freeze_layout_encoder: bool = True,
        fusion: str = "concat_cross_attention",
        use_flag_embedding: bool = True,
        use_multitask: bool = False,
        global_task_embedding: bool = False,
        relation_size: int = 10,
        image_channels: int = 4,
        image_size: tuple[int, int] | list[int] | None = None,
        sort_order: Sequence[str] = ("label", "lexicographic"),
        retrieval_metadata: RalfConfigMetadata | None = None,
        original_config: RalfConfigMetadata | None = None,
        original_hydra_config: RalfConfigMetadata | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Initialize configuration values."""
        labels = (
            id2label_for_dataset(dataset_name)
            if id2label is None
            else {int(k): str(v) for k, v in id2label.items()}
        )

        self.dataset_name = dataset_name
        self.task = task
        self.id2label = labels
        self.max_seq_length = int(max_seq_length)
        self.num_bin = int(num_bin)
        self.var_order = tuple(var_order)
        self.special_tokens = tuple(special_tokens)
        self.geo_quantization = geo_quantization
        self.is_loc_vocab_shared = bool(is_loc_vocab_shared)

        self.d_model = int(d_model)
        self.decoder_d_model = int(decoder_d_model)
        self.encoder_layers = int(encoder_layers)
        self.decoder_layers = int(decoder_layers)
        self.num_attention_heads = int(num_attention_heads)
        self.dropout = float(dropout)

        self.retrieval_backbone = retrieval_backbone
        self.saliency_k = saliency_k
        self.top_k = int(top_k)
        self.use_reference_image = bool(use_reference_image)
        self.layout_backbone = layout_backbone
        self.freeze_layout_encoder = bool(freeze_layout_encoder)

        self.fusion = fusion
        self.use_flag_embedding = bool(use_flag_embedding)
        self.use_multitask = bool(use_multitask)
        self.global_task_embedding = bool(global_task_embedding)

        self.relation_size = int(relation_size)
        self.image_channels = int(image_channels)
        self.image_size = tuple(image_size) if image_size is not None else None
        self.sort_order = tuple(sort_order)
        self.retrieval_metadata = dict(retrieval_metadata or {})
        self.original_config = dict(original_config or original_hydra_config or {})
        self.original_hydra_config = self.original_config

        pad_token_id = self.special_token_id("pad")
        bos_token_id = self.special_token_id("bos")
        eos_token_id = self.special_token_id("eos")
        kwargs.pop("model_type", None)
        kwargs.pop("id2label", None)
        kwargs.pop("label2id", None)
        kwargs.pop("pad_token_id", None)
        kwargs.pop("bos_token_id", None)
        kwargs.pop("eos_token_id", None)

        super().__init__(
            id2label=self.id2label,
            label2id={label: idx for idx, label in self.id2label.items()},
        )
        self.pad_token_id = pad_token_id
        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id
        for key, value in kwargs.items():
            setattr(self, key, value)

    @property
    def num_bbox_tokens(self) -> int:
        """Return the number of geometry tokens."""
        return self.num_bin if self.is_loc_vocab_shared else self.num_bin * 4

    @property
    def vocab_size(self) -> int:
        """Return total autoregressive token vocabulary size."""
        return self.num_labels + self.num_bbox_tokens + len(self.special_tokens)

    @property
    def max_token_length(self) -> int:
        """Return maximum generated token length excluding BOS."""
        return self.max_seq_length * len(self.var_order)

    def special_token_id(self, name: str) -> int:
        """Return the numeric id for a special token name.

        Args:
            name: Special token name without brackets.

        Returns:
            Numeric token id.

        Raises:
            ValueError: If the token is absent from this config.
        """
        if name not in self.special_tokens:
            raise ValueError(f"Unknown special token: {name}")

        return self.num_labels + self.num_bbox_tokens + self.special_tokens.index(name)

    def bbox_token_offset(self, key: RalfLayoutVariable) -> int:
        """Return the first token id for a geometry variable."""
        if key == "label":
            return 0
        if self.is_loc_vocab_shared:
            return self.num_labels
        return self.num_labels + GEOMETRY_KEYS.index(key) * self.num_bin

num_bbox_tokens property

num_bbox_tokens: int

Return the number of geometry tokens.

vocab_size property

vocab_size: int

Return total autoregressive token vocabulary size.

max_token_length property

max_token_length: int

Return maximum generated token length excluding BOS.

__init__

__init__(
    dataset_name: RalfDatasetName = "cgl",
    task: RalfConfigTaskName = "unconditional",
    id2label: Mapping[int | str, str] | None = None,
    max_seq_length: int = 10,
    num_bin: int = 128,
    var_order: Sequence[
        RalfLayoutVariable
    ] = DEFAULT_VAR_ORDER,
    special_tokens: Sequence[str] = DEFAULT_SPECIAL_TOKENS,
    geo_quantization: str = "linear",
    is_loc_vocab_shared: bool = False,
    d_model: int = 256,
    decoder_d_model: int = 256,
    encoder_layers: int = 6,
    decoder_layers: int = 6,
    num_attention_heads: int = 8,
    dropout: float = 0.1,
    retrieval_backbone: str = "dreamsim",
    saliency_k: int | str = "None",
    top_k: int = 16,
    use_reference_image: bool = False,
    layout_backbone: str = "feature_extractor",
    freeze_layout_encoder: bool = True,
    fusion: str = "concat_cross_attention",
    use_flag_embedding: bool = True,
    use_multitask: bool = False,
    global_task_embedding: bool = False,
    relation_size: int = 10,
    image_channels: int = 4,
    image_size: tuple[int, int] | list[int] | None = None,
    sort_order: Sequence[str] = ("label", "lexicographic"),
    retrieval_metadata: RalfConfigMetadata | None = None,
    original_config: RalfConfigMetadata | None = None,
    original_hydra_config: RalfConfigMetadata | None = None,
    **kwargs: str | int | float | bool | None,
) -> None

Initialize configuration values.

Source code in models/ralf/src/ralf/configuration_ralf.py
 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
def __init__(
    self,
    dataset_name: RalfDatasetName = "cgl",
    task: RalfConfigTaskName = "unconditional",
    id2label: Mapping[int | str, str] | None = None,
    max_seq_length: int = 10,
    num_bin: int = 128,
    var_order: Sequence[RalfLayoutVariable] = DEFAULT_VAR_ORDER,
    special_tokens: Sequence[str] = DEFAULT_SPECIAL_TOKENS,
    geo_quantization: str = "linear",
    is_loc_vocab_shared: bool = False,
    d_model: int = 256,
    decoder_d_model: int = 256,
    encoder_layers: int = 6,
    decoder_layers: int = 6,
    num_attention_heads: int = 8,
    dropout: float = 0.1,
    retrieval_backbone: str = "dreamsim",
    saliency_k: int | str = "None",
    top_k: int = 16,
    use_reference_image: bool = False,
    layout_backbone: str = "feature_extractor",
    freeze_layout_encoder: bool = True,
    fusion: str = "concat_cross_attention",
    use_flag_embedding: bool = True,
    use_multitask: bool = False,
    global_task_embedding: bool = False,
    relation_size: int = 10,
    image_channels: int = 4,
    image_size: tuple[int, int] | list[int] | None = None,
    sort_order: Sequence[str] = ("label", "lexicographic"),
    retrieval_metadata: RalfConfigMetadata | None = None,
    original_config: RalfConfigMetadata | None = None,
    original_hydra_config: RalfConfigMetadata | None = None,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Initialize configuration values."""
    labels = (
        id2label_for_dataset(dataset_name)
        if id2label is None
        else {int(k): str(v) for k, v in id2label.items()}
    )

    self.dataset_name = dataset_name
    self.task = task
    self.id2label = labels
    self.max_seq_length = int(max_seq_length)
    self.num_bin = int(num_bin)
    self.var_order = tuple(var_order)
    self.special_tokens = tuple(special_tokens)
    self.geo_quantization = geo_quantization
    self.is_loc_vocab_shared = bool(is_loc_vocab_shared)

    self.d_model = int(d_model)
    self.decoder_d_model = int(decoder_d_model)
    self.encoder_layers = int(encoder_layers)
    self.decoder_layers = int(decoder_layers)
    self.num_attention_heads = int(num_attention_heads)
    self.dropout = float(dropout)

    self.retrieval_backbone = retrieval_backbone
    self.saliency_k = saliency_k
    self.top_k = int(top_k)
    self.use_reference_image = bool(use_reference_image)
    self.layout_backbone = layout_backbone
    self.freeze_layout_encoder = bool(freeze_layout_encoder)

    self.fusion = fusion
    self.use_flag_embedding = bool(use_flag_embedding)
    self.use_multitask = bool(use_multitask)
    self.global_task_embedding = bool(global_task_embedding)

    self.relation_size = int(relation_size)
    self.image_channels = int(image_channels)
    self.image_size = tuple(image_size) if image_size is not None else None
    self.sort_order = tuple(sort_order)
    self.retrieval_metadata = dict(retrieval_metadata or {})
    self.original_config = dict(original_config or original_hydra_config or {})
    self.original_hydra_config = self.original_config

    pad_token_id = self.special_token_id("pad")
    bos_token_id = self.special_token_id("bos")
    eos_token_id = self.special_token_id("eos")
    kwargs.pop("model_type", None)
    kwargs.pop("id2label", None)
    kwargs.pop("label2id", None)
    kwargs.pop("pad_token_id", None)
    kwargs.pop("bos_token_id", None)
    kwargs.pop("eos_token_id", None)

    super().__init__(
        id2label=self.id2label,
        label2id={label: idx for idx, label in self.id2label.items()},
    )
    self.pad_token_id = pad_token_id
    self.bos_token_id = bos_token_id
    self.eos_token_id = eos_token_id
    for key, value in kwargs.items():
        setattr(self, key, value)

special_token_id

special_token_id(name: str) -> int

Return the numeric id for a special token name.

Parameters:

Name Type Description Default
name str

Special token name without brackets.

required

Returns:

Type Description
int

Numeric token id.

Raises:

Type Description
ValueError

If the token is absent from this config.

Source code in models/ralf/src/ralf/configuration_ralf.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def special_token_id(self, name: str) -> int:
    """Return the numeric id for a special token name.

    Args:
        name: Special token name without brackets.

    Returns:
        Numeric token id.

    Raises:
        ValueError: If the token is absent from this config.
    """
    if name not in self.special_tokens:
        raise ValueError(f"Unknown special token: {name}")

    return self.num_labels + self.num_bbox_tokens + self.special_tokens.index(name)

bbox_token_offset

bbox_token_offset(key: RalfLayoutVariable) -> int

Return the first token id for a geometry variable.

Source code in models/ralf/src/ralf/configuration_ralf.py
231
232
233
234
235
236
237
def bbox_token_offset(self, key: RalfLayoutVariable) -> int:
    """Return the first token id for a geometry variable."""
    if key == "label":
        return 0
    if self.is_loc_vocab_shared:
        return self.num_labels
    return self.num_labels + GEOMETRY_KEYS.index(key) * self.num_bin

datasets

Dataset adapters for RALF-compatible poster layouts.

normalize_org_sample

normalize_org_sample(
    sample: RalfSampleMapping,
    dataset_name: DatasetName | str,
) -> RalfNormalizedSample

Normalize one org-dataset sample to RALF-style fields.

Parameters:

Name Type Description Default
sample RalfSampleMapping

Dataset row.

required
dataset_name DatasetName | str

Poster dataset key.

required

Returns:

Type Description
RalfNormalizedSample

Dictionary with normalized public layout fields.

Raises:

Type Description
ValueError

If the dataset is unsupported.

Source code in models/ralf/src/ralf/datasets.py
 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
def normalize_org_sample(
    sample: RalfSampleMapping, dataset_name: DatasetName | str
) -> RalfNormalizedSample:
    """Normalize one org-dataset sample to RALF-style fields.

    Args:
        sample: Dataset row.
        dataset_name: Poster dataset key.

    Returns:
        Dictionary with normalized public layout fields.

    Raises:
        ValueError: If the dataset is unsupported.
    """
    dataset = normalize_dataset_name(dataset_name)
    if {"label", "center_x", "center_y", "width", "height"}.issubset(sample):
        labels = _labels_to_tensor(
            cast(Sequence[int | str] | Int[torch.Tensor, "elements"], sample["label"]),
            dataset,
        )
        bbox = torch.stack(
            [
                torch.as_tensor(sample["center_x"], dtype=torch.float32),
                torch.as_tensor(sample["center_y"], dtype=torch.float32),
                torch.as_tensor(sample["width"], dtype=torch.float32),
                torch.as_tensor(sample["height"], dtype=torch.float32),
            ],
            dim=-1,
        )
        return {
            "bbox": bbox,
            "labels": labels,
            "mask": torch.ones(labels.shape, dtype=torch.bool),
        }
    if dataset in {DatasetName.cgl, DatasetName.cgl_v2}:
        annotations_obj = sample.get("annotations", {})
        annotations = annotations_obj if isinstance(annotations_obj, Mapping) else {}
        bbox = torch.as_tensor(annotations.get("bbox", []), dtype=torch.float32)
        if bbox.numel() == 0:
            bbox = bbox.reshape(0, 4)
        labels = torch.as_tensor(annotations.get("category", []), dtype=torch.long)
        width_obj = sample.get("width", 1)
        height_obj = sample.get("height", 1)
        width = int(width_obj) if isinstance(width_obj, int | float | str) else 1
        height = int(height_obj) if isinstance(height_obj, int | float | str) else 1
        scale = torch.tensor((width, height, width, height), dtype=torch.float32)
        bbox = ltwh_to_xywh(bbox / scale)
        return {
            "bbox": bbox,
            "labels": labels,
            "mask": torch.ones(labels.shape, dtype=torch.bool),
        }
    if dataset is DatasetName.pku_posterlayout:
        annotations_obj = sample.get("annotations", {})
        annotations = annotations_obj if isinstance(annotations_obj, Mapping) else {}
        bbox = torch.as_tensor(annotations.get("box_elem", []), dtype=torch.float32)
        if bbox.numel() == 0:
            bbox = bbox.reshape(0, 4)
        labels = torch.as_tensor(annotations.get("cls_elem", []), dtype=torch.long)
        valid = labels.ne(3)
        size = sample.get("poster") or sample.get("canvas") or sample.get("image")
        width, height = getattr(size, "size", (1, 1))
        scale = torch.tensor((width, height, width, height), dtype=torch.float32)
        bbox = ltrb_to_xywh(bbox / scale)
        return {
            "bbox": bbox[valid],
            "labels": labels[valid],
            "mask": torch.ones(int(valid.sum()), dtype=torch.bool),
        }
    raise ValueError(f"Unsupported RALF dataset: {dataset_name}")

load_ralf_dataset

load_ralf_dataset(
    dataset_name: Literal[
        "cgl", "cgl_v2", "pku_posterlayout"
    ],
    split: str,
    *,
    source: Literal["hf_org"] = "hf_org",
) -> _IndexableDataset

Load a RALF-compatible dataset lazily.

Parameters:

Name Type Description Default
dataset_name Literal['cgl', 'cgl_v2', 'pku_posterlayout']

Canonical poster dataset name.

required
split str

Dataset split.

required
source Literal['hf_org']

Data source. Only hf_org is supported.

'hf_org'

Returns:

Type Description
_IndexableDataset

Hugging Face dataset object.

Raises:

Type Description
ValueError

If the source or dataset is unsupported.

Source code in models/ralf/src/ralf/datasets.py
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
def load_ralf_dataset(
    dataset_name: Literal["cgl", "cgl_v2", "pku_posterlayout"],
    split: str,
    *,
    source: Literal["hf_org"] = "hf_org",
) -> _IndexableDataset:
    """Load a RALF-compatible dataset lazily.

    Args:
        dataset_name: Canonical poster dataset name.
        split: Dataset split.
        source: Data source. Only `hf_org` is supported.

    Returns:
        Hugging Face dataset object.

    Raises:
        ValueError: If the source or dataset is unsupported.
    """
    if source != "hf_org":
        raise ValueError("Only source='hf_org' is supported")

    try:
        from datasets import load_dataset
    except ImportError as exc:  # pragma: no cover - optional dependency
        raise ImportError(
            "Install the optional reference dependencies to load org datasets"
        ) from exc

    dataset = normalize_dataset_name(dataset_name)
    if dataset is DatasetName.cgl:
        return cast(
            _IndexableDataset,
            load_dataset(
                "creative-graphic-design/CGL-Dataset", name="ralf-style", split=split
            ),
        )
    if dataset is DatasetName.cgl_v2:
        return cast(
            _IndexableDataset,
            load_dataset(
                "creative-graphic-design/CGL-Dataset-v2", name="ralf-style", split=split
            ),
        )
    if dataset is DatasetName.pku_posterlayout:
        return cast(
            _IndexableDataset,
            load_dataset(
                "creative-graphic-design/PKU-PosterLayout",
                name="ralf-style",
                split=split,
            ),
        )
    raise ValueError(f"Unsupported RALF dataset: {dataset_name}")

build_retrieved_batch

build_retrieved_batch(
    dataset: _IndexableDataset,
    indexes: Int[Tensor, "batch candidates"],
    *,
    max_seq_length: int,
    dataset_name: RalfDatasetName = "cgl",
) -> RalfRetrievedBatch

Build explicit retrieved layout tensors from dataset indexes.

Parameters:

Name Type Description Default
dataset _IndexableDataset

Indexable dataset whose rows match normalize_org_sample.

required
indexes Int[Tensor, 'batch candidates']

Tensor of retrieved row indexes with shape (batch, candidates).

required
max_seq_length int

Maximum elements retained per layout.

required
dataset_name RalfDatasetName

Dataset key used for row normalization. PKU labels are remapped from org dataset ids (text=0, logo=1, underlay=2) to the checkpoint ids (logo=0, text=1, underlay=2) used by converted RALF.

'cgl'

Returns:

Type Description
RalfRetrievedBatch

Retrieved batch with layout fields filled and image tensors as zeros.

Source code in models/ralf/src/ralf/datasets.py
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
def build_retrieved_batch(
    dataset: _IndexableDataset,
    indexes: Int[torch.Tensor, "batch candidates"],
    *,
    max_seq_length: int,
    dataset_name: RalfDatasetName = "cgl",
) -> RalfRetrievedBatch:
    """Build explicit retrieved layout tensors from dataset indexes.

    Args:
        dataset: Indexable dataset whose rows match `normalize_org_sample`.
        indexes: Tensor of retrieved row indexes with shape `(batch, candidates)`.
        max_seq_length: Maximum elements retained per layout.
        dataset_name: Dataset key used for row normalization. PKU labels are remapped
            from org dataset ids (`text=0`, `logo=1`, `underlay=2`) to the checkpoint
            ids (`logo=0`, `text=1`, `underlay=2`) used by converted RALF.

    Returns:
        Retrieved batch with layout fields filled and image tensors as zeros.
    """
    normalized_dataset = normalize_dataset_name(dataset_name)
    bbox_rows = []
    label_rows = []
    mask_rows = []
    for row in indexes.tolist():
        bbox_candidates = []
        label_candidates = []
        mask_candidates = []
        for idx in row:
            sample = normalize_org_sample(dataset[int(idx)], normalized_dataset)
            bbox = torch.zeros(max_seq_length, 4)
            labels = torch.zeros(max_seq_length, dtype=torch.long)
            mask: Bool[torch.Tensor, "elements"] = torch.zeros(
                max_seq_length, dtype=torch.bool
            )
            sample_labels = _remap_retrieval_labels(
                cast(Int[torch.Tensor, "sample_elements"], sample["labels"]).long(),
                normalized_dataset,
            )
            sample_bbox = cast(Float[torch.Tensor, "sample_elements 4"], sample["bbox"])
            length = min(max_seq_length, sample_labels.numel())
            bbox[:length] = sample_bbox[:length]
            labels[:length] = sample_labels[:length]
            mask[:length] = True

            bbox_candidates.append(bbox)
            label_candidates.append(labels)
            mask_candidates.append(mask)

        bbox_rows.append(torch.stack(bbox_candidates))
        label_rows.append(torch.stack(label_candidates))
        mask_rows.append(torch.stack(mask_candidates))
    bbox_tensor = torch.stack(bbox_rows)
    labels_tensor = torch.stack(label_rows)
    mask_tensor = torch.stack(mask_rows)

    batch, candidates = indexes.shape
    return RalfRetrievedBatch(
        image=torch.zeros(batch, candidates, 3, 1, 1),
        saliency=torch.zeros(batch, candidates, 1, 1, 1),
        bbox=bbox_tensor,
        labels=labels_tensor,
        mask=mask_tensor,
        indexes=indexes,
    )

image_processing_ralf

Image processor for RALF content images and saliency maps.

RalfImageProcessor

Bases: BaseImageProcessor

Prepare RGB poster images and one-channel saliency tensors.

Parameters:

Name Type Description Default
image_size tuple[int, int] | None

Optional (height, width) resize target.

None

Examples:

>>> processor = RalfImageProcessor(image_size=(8, 8))
>>> out = processor.preprocess([torch.zeros(3, 8, 8)])
>>> tuple(out["pixel_values"].shape)
(1, 3, 8, 8)
Source code in models/ralf/src/ralf/image_processing_ralf.py
 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
class RalfImageProcessor(BaseImageProcessor):
    """Prepare RGB poster images and one-channel saliency tensors.

    Args:
        image_size: Optional `(height, width)` resize target.

    Examples:
        >>> processor = RalfImageProcessor(image_size=(8, 8))
        >>> out = processor.preprocess([torch.zeros(3, 8, 8)])
        >>> tuple(out["pixel_values"].shape)
        (1, 3, 8, 8)
    """

    model_input_names = ["pixel_values", "saliency"]

    def __init__(
        self,
        image_size: tuple[int, int] | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Initialize image resize metadata."""
        super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
        self.image_size = tuple(image_size) if image_size is not None else None

    def preprocess(
        self,
        images: ImageInput | Sequence[ImageInput] | None,
        saliency: ImageInput | Sequence[ImageInput] | None = None,
        return_tensors: Literal["pt"] = "pt",
        **kwargs: str | int | float | bool | None,
    ) -> BatchFeature:
        """Convert images and saliency maps to tensors.

        Args:
            images: RGB images as PIL, NumPy, or torch tensors.
            saliency: Optional single-channel saliency maps.
            return_tensors: Tensor return format. Only `pt` is supported.
            kwargs: Reserved processor arguments.

        Returns:
            BatchFeature with `pixel_values` and `saliency`.

        Raises:
            ValueError: If `return_tensors` is not `pt`.
        """
        _ = kwargs
        if return_tensors != "pt":
            raise ValueError("RalfImageProcessor supports return_tensors='pt' only")

        image_items = (
            _as_list(images) if images is not None else [torch.zeros(3, 64, 64)]
        )
        pixel_values = torch.stack(
            [_image_to_tensor(item, channels=3) for item in image_items]
        )
        if self.image_size is not None:
            pixel_values = torch.nn.functional.interpolate(
                pixel_values,
                size=self.image_size,
                mode="bilinear",
                align_corners=False,
            )
        if saliency is None:
            saliency_values = torch.zeros(
                pixel_values.size(0),
                1,
                pixel_values.size(2),
                pixel_values.size(3),
                dtype=pixel_values.dtype,
            )
        else:
            saliency_items = _as_list(saliency)
            if len(saliency_items) == 1 and pixel_values.size(0) > 1:
                saliency_items = saliency_items * pixel_values.size(0)
            saliency_values = torch.stack(
                [_image_to_tensor(item, channels=1) for item in saliency_items]
            )
            if self.image_size is not None:
                saliency_values = torch.nn.functional.interpolate(
                    saliency_values,
                    size=self.image_size,
                    mode="bilinear",
                    align_corners=False,
                )
        return BatchFeature(
            {"pixel_values": pixel_values, "saliency": saliency_values},
            tensor_type=return_tensors,
        )

    def to_dict(self) -> dict[str, RalfImageProcessorConfigValue]:
        """Serialize image processor metadata."""
        data = cast(dict[str, RalfImageProcessorConfigValue], super().to_dict())
        data["image_size"] = self.image_size
        return data

__init__

__init__(
    image_size: tuple[int, int] | None = None,
    **kwargs: str | int | float | bool | None,
) -> None

Initialize image resize metadata.

Source code in models/ralf/src/ralf/image_processing_ralf.py
71
72
73
74
75
76
77
78
def __init__(
    self,
    image_size: tuple[int, int] | None = None,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Initialize image resize metadata."""
    super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
    self.image_size = tuple(image_size) if image_size is not None else None

preprocess

preprocess(
    images: ImageInput | Sequence[ImageInput] | None,
    saliency: ImageInput
    | Sequence[ImageInput]
    | None = None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: str | int | float | bool | None,
) -> BatchFeature

Convert images and saliency maps to tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

RGB images as PIL, NumPy, or torch tensors.

required
saliency ImageInput | Sequence[ImageInput] | None

Optional single-channel saliency maps.

None
return_tensors Literal['pt']

Tensor return format. Only pt is supported.

'pt'
kwargs str | int | float | bool | None

Reserved processor arguments.

{}

Returns:

Type Description
BatchFeature

BatchFeature with pixel_values and saliency.

Raises:

Type Description
ValueError

If return_tensors is not pt.

Source code in models/ralf/src/ralf/image_processing_ralf.py
 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
def preprocess(
    self,
    images: ImageInput | Sequence[ImageInput] | None,
    saliency: ImageInput | Sequence[ImageInput] | None = None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: str | int | float | bool | None,
) -> BatchFeature:
    """Convert images and saliency maps to tensors.

    Args:
        images: RGB images as PIL, NumPy, or torch tensors.
        saliency: Optional single-channel saliency maps.
        return_tensors: Tensor return format. Only `pt` is supported.
        kwargs: Reserved processor arguments.

    Returns:
        BatchFeature with `pixel_values` and `saliency`.

    Raises:
        ValueError: If `return_tensors` is not `pt`.
    """
    _ = kwargs
    if return_tensors != "pt":
        raise ValueError("RalfImageProcessor supports return_tensors='pt' only")

    image_items = (
        _as_list(images) if images is not None else [torch.zeros(3, 64, 64)]
    )
    pixel_values = torch.stack(
        [_image_to_tensor(item, channels=3) for item in image_items]
    )
    if self.image_size is not None:
        pixel_values = torch.nn.functional.interpolate(
            pixel_values,
            size=self.image_size,
            mode="bilinear",
            align_corners=False,
        )
    if saliency is None:
        saliency_values = torch.zeros(
            pixel_values.size(0),
            1,
            pixel_values.size(2),
            pixel_values.size(3),
            dtype=pixel_values.dtype,
        )
    else:
        saliency_items = _as_list(saliency)
        if len(saliency_items) == 1 and pixel_values.size(0) > 1:
            saliency_items = saliency_items * pixel_values.size(0)
        saliency_values = torch.stack(
            [_image_to_tensor(item, channels=1) for item in saliency_items]
        )
        if self.image_size is not None:
            saliency_values = torch.nn.functional.interpolate(
                saliency_values,
                size=self.image_size,
                mode="bilinear",
                align_corners=False,
            )
    return BatchFeature(
        {"pixel_values": pixel_values, "saliency": saliency_values},
        tensor_type=return_tensors,
    )

to_dict

to_dict() -> dict[str, RalfImageProcessorConfigValue]

Serialize image processor metadata.

Source code in models/ralf/src/ralf/image_processing_ralf.py
145
146
147
148
149
def to_dict(self) -> dict[str, RalfImageProcessorConfigValue]:
    """Serialize image processor metadata."""
    data = cast(dict[str, RalfImageProcessorConfigValue], super().to_dict())
    data["image_size"] = self.image_size
    return data

modeling_ralf

PyTorch model wrapper for standalone RALF checkpoints.

RalfRelationNamedItem

Bases: Protocol

Relation enum-like item with a name field.

Source code in models/ralf/src/ralf/modeling_ralf.py
68
69
70
71
72
@runtime_checkable
class RalfRelationNamedItem(Protocol):
    """Relation enum-like item with a name field."""

    name: str

ImageReshaper

Bases: Module

Reshape image feature maps to transformer memory.

Source code in models/ralf/src/ralf/modeling_ralf.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class ImageReshaper(nn.Module):
    """Reshape image feature maps to transformer memory."""

    def __init__(self, d_model: int) -> None:
        super().__init__()
        self.d_model = d_model

    def forward(
        self, x: Float[torch.Tensor, "batch channels height width"]
    ) -> Float[torch.Tensor, "batch pixels channels"]:
        if x.size(1) != self.d_model:
            raise ValueError(f"{x.size(1)} != {self.d_model}")

        return rearrange(x, "b c h w -> b (h w) c")

PositionalEncoding1d

Bases: Module

RALF sine positional encoding for token sequences.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class PositionalEncoding1d(nn.Module):
    """RALF sine positional encoding for token sequences."""

    pe: (
        Float[torch.Tensor, "1 max_len d_model"]
        | Float[torch.Tensor, "max_len 1 d_model"]
    )

    def __init__(
        self,
        d_model: int,
        dropout: float = 0.1,
        max_len: int = 5000,
        batch_first: bool = True,
        scale_input: bool = True,
    ) -> None:
        super().__init__()
        self.d_model = d_model
        self.dropout = nn.Dropout(p=dropout)
        self.batch_first = batch_first
        self.scale_input = scale_input
        position = torch.arange(max_len).unsqueeze(1)
        div_term = torch.exp(
            torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)
        )
        if batch_first:
            pe = torch.zeros(1, max_len, d_model)
            pe[0, :, 0::2] = torch.sin(position * div_term)
            pe[0, :, 1::2] = torch.cos(position * div_term)
        else:
            pe = torch.zeros(max_len, 1, d_model)
            pe[:, 0, 0::2] = torch.sin(position * div_term)
            pe[:, 0, 1::2] = torch.cos(position * div_term)
        self.register_buffer("pe", pe)

    def forward(
        self, x: Float[torch.Tensor, "... channels"]
    ) -> Float[torch.Tensor, "... channels"]:
        h = x * math.sqrt(self.d_model) if self.scale_input else x
        if self.batch_first:
            h = h + self.pe[:, : h.size(1)]
        else:
            h = h + self.pe[: h.size(0)]
        return self.dropout(h)

PositionEmbeddingSine

Bases: Module

RALF 2D sine positional encoding.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class PositionEmbeddingSine(nn.Module):
    """RALF 2D sine positional encoding."""

    def __init__(
        self,
        d_model: int = 256,
        temperature: int = 10000,
        normalize: bool = False,
        scale: float | None = None,
    ) -> None:
        super().__init__()
        self.d_model = d_model // 2
        self.temperature = temperature
        self.normalize = normalize
        if scale is not None and not normalize:
            raise ValueError("normalize should be True if scale is passed")

        self.scale = 2 * math.pi if scale is None else scale
        self.reshape = ImageReshaper(d_model)

    def forward(
        self, input: Float[torch.Tensor, "batch channels height width"]
    ) -> Float[torch.Tensor, "batch pixels channels"]:
        bs, _c, h, w = input.size()
        y, x = torch.meshgrid(
            torch.arange(h).type_as(input),
            torch.arange(w).type_as(input),
            indexing="ij",
        )
        if self.normalize:
            y = y / (h - 1)
            x = x / (w - 1)
            y = y * self.scale
            x = x * self.scale
        dim_t = torch.arange(self.d_model).type_as(input)
        dim_t = self.temperature ** (
            2 * torch.div(dim_t, 2, rounding_mode="floor") / self.d_model
        )
        pos_x = x.flatten()[None, :, None] / dim_t
        pos_y = y.flatten()[None, :, None] / dim_t
        pos_x = torch.stack(
            (pos_x[..., 0::2].sin(), pos_x[..., 1::2].cos()), dim=3
        ).flatten(2)
        pos_y = torch.stack(
            (pos_y[..., 0::2].sin(), pos_y[..., 1::2].cos()), dim=3
        ).flatten(2)
        pos = torch.cat((pos_y, pos_x), dim=2).repeat(bs, 1, 1)
        return self.reshape(input) + pos

FeedForward

Bases: Module

RALF MLP block.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class FeedForward(nn.Module):
    """RALF MLP block."""

    def __init__(
        self,
        dim: int,
        hidden_dim: int,
        dropout: float = 0.0,
        output_dim: int | None = None,
    ) -> None:
        super().__init__()
        output_dim = dim if output_dim is None else output_dim
        self.net = nn.Sequential(
            nn.LayerNorm(dim),
            nn.Linear(dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, output_dim),
            nn.Dropout(dropout),
        )

    def forward(
        self, x: Float[torch.Tensor, "... channels"]
    ) -> Float[torch.Tensor, "... output_channels"]:
        return self.net(x)

Attention

Bases: Module

RALF cross-attention block.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class Attention(nn.Module):
    """RALF cross-attention block."""

    def __init__(
        self,
        dim_q: int,
        dimvq: int,
        heads: int = 8,
        dim_head: int = 64,
        dropout: float = 0.0,
    ) -> None:
        super().__init__()
        inner_dim = dim_head * heads
        self.heads = heads
        self.scale = dim_head**-0.5
        self.norm = nn.LayerNorm(dim_q)
        self.attend = nn.Softmax(dim=-1)
        self.dropout = nn.Dropout(dropout)
        self.to_q = nn.Linear(dim_q, inner_dim, bias=False)
        self.to_kv = nn.Linear(dimvq, inner_dim * 2, bias=False)
        self.to_out = nn.Sequential(nn.Linear(inner_dim, dim_q), nn.Dropout(dropout))

    def forward(
        self,
        x: Float[torch.Tensor, "batch query channels"],
        context: Float[torch.Tensor, "batch key channels"] | None = None,
        kv_include_self: bool = False,
    ) -> Float[torch.Tensor, "batch query channels"]:
        b, _n, _d = x.shape
        h = self.heads
        x = self.norm(x)
        context = x if context is None else context
        if kv_include_self:
            context = torch.cat((x, context), dim=1)
        qkv = (self.to_q(x), *self.to_kv(context).chunk(2, dim=-1))
        q, k, v = (rearrange(t, "b n (h d) -> b h n d", h=h) for t in qkv)
        dots = einsum("b h i d, b h j d -> b h i j", q, k) * self.scale
        attn = self.dropout(self.attend(dots))
        out = einsum("b h i j, b h j d -> b h i d", attn, v)
        out = rearrange(out, "b h n d -> b n (h d)", b=b)
        return self.to_out(out)

ResnetBackbone

Bases: Module

RALF ResNet50 FPN feature extractor without external loads.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class ResnetBackbone(nn.Module):
    """RALF ResNet50 FPN feature extractor without external loads."""

    def __init__(
        self, backbone: str = "resnet50", d_model: int = 256, head: str = "transformer"
    ) -> None:
        super().__init__()
        if backbone != "resnet50":
            raise ValueError("RALF converted checkpoints use resnet50")

        resnet = timm.create_model("resnet50", pretrained=False)
        return_nodes = {"layer4": "layer4", "layer3": "layer3"}
        self.body = create_feature_extractor(resnet, return_nodes=return_nodes)
        params = {
            key: getattr(self.body.conv1, key)
            for key in ["kernel_size", "stride", "padding", "out_channels"]
        }
        conv1 = cast(nn.Conv2d, self.body.conv1)
        weight = conv1.weight.data
        weight = torch.cat([weight, torch.mean(weight, dim=1, keepdim=True)], dim=1)
        self.body.conv1 = nn.Conv2d(in_channels=4, bias=False, **params)
        self.body.conv1.weight.data = weight
        self.fpn_conv11_4 = nn.Conv2d(1024, 256, 1, 1, 0)
        self.fpn_conv11_5 = nn.Conv2d(2048, 256, 1, 1, 0)
        self.fpn_conv33 = nn.Conv2d(256, 256, 3, 1, 1)
        self.proj = nn.Conv2d(512, d_model, 1, 1, 0)
        if head != "transformer":
            raise ValueError("RALF converted checkpoints use transformer image head")

        self.head = head

    def forward(
        self, img: Float[torch.Tensor, "batch channels height width"]
    ) -> Float[torch.Tensor, "batch out_channels out_height out_width"]:
        h = self.body(img)
        resnet_f4 = h["layer3"]
        resnet_f5 = h["layer4"]
        resnet_f4p = self.fpn_conv11_4(resnet_f4)
        resnet_f5p = self.fpn_conv11_5(resnet_f5)
        resnet_f5up = F.interpolate(
            resnet_f5p, size=resnet_f4p.shape[2:], mode="nearest"
        )
        resnet_fused = torch.concat(
            [resnet_f5up, self.fpn_conv33(resnet_f5up + resnet_f4p)], dim=1
        )
        return self.proj(resnet_fused)

ResnetFeatureExtractor

Bases: Module

Container preserving checkpoint key prefix.

Source code in models/ralf/src/ralf/modeling_ralf.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
class ResnetFeatureExtractor(nn.Module):
    """Container preserving checkpoint key prefix."""

    def __init__(
        self,
        backbone: str = "resnet50",
        d_model: int = 256,
        head: str = "transformer",
    ) -> None:
        super().__init__()
        self.extractor = ResnetBackbone(backbone=backbone, d_model=d_model, head=head)

    def forward(
        self, img: Float[torch.Tensor, "batch channels height width"]
    ) -> Float[torch.Tensor, "batch channels height width"]:
        return self.extractor(img)

TransformerWithToken

Bases: Module

FIDNet transformer encoder with a learned summary token.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class TransformerWithToken(nn.Module):
    """FIDNet transformer encoder with a learned summary token."""

    token_mask: Bool[torch.Tensor, "1 1"]

    def __init__(
        self, d_model: int, nhead: int, dim_feedforward: int, num_layers: int
    ) -> None:
        super().__init__()
        self.token = nn.Parameter(torch.randn(1, 1, d_model))
        self.register_buffer("token_mask", torch.zeros(1, 1, dtype=torch.bool))
        self.core = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d_model=d_model,
                nhead=nhead,
                dim_feedforward=dim_feedforward,
            ),
            num_layers=num_layers,
        )

    def forward(
        self,
        x: Float[torch.Tensor, "tokens batch channels"],
        src_key_padding_mask: Bool[torch.Tensor, "batch tokens"],
    ) -> Float[torch.Tensor, "tokens batch channels"]:
        batch = x.size(1)
        token = self.token.expand(-1, batch, -1)
        x = torch.cat([token, x], dim=0)
        token_mask = self.token_mask.expand(batch, -1)
        padding_mask = torch.cat([token_mask, src_key_padding_mask], dim=1)
        return self.core(x, src_key_padding_mask=padding_mask)

FIDNetFeatureExtractor

Bases: Module

FIDNet encoder subset used by RALF retrieval layout features.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class FIDNetFeatureExtractor(nn.Module):
    """FIDNet encoder subset used by RALF retrieval layout features."""

    def __init__(
        self,
        num_label: int,
        d_model: int = 256,
        nhead: int = 4,
        num_layers: int = 4,
        max_bbox: int = 10,
    ) -> None:
        super().__init__()
        _ = max_bbox
        self.emb_label = nn.Embedding(num_label, d_model)
        self.fc_bbox = nn.Linear(4, d_model)
        self.enc_fc_in = nn.Linear(d_model * 2, d_model)
        self.enc_transformer = TransformerWithToken(
            d_model=d_model,
            dim_feedforward=d_model // 2,
            nhead=nhead,
            num_layers=num_layers,
        )
        self.dec_fc_in = nn.Linear(d_model * 2, d_model)

    def extract_features(
        self, inputs: Mapping[str, Shaped[torch.Tensor, ...]]
    ) -> Float[torch.Tensor, "batch channels"]:
        padding_mask = ~inputs["mask"]
        bbox = torch.stack([inputs[key] for key in FID_BBOX_KEYS], dim=-1)
        h_bbox = self.fc_bbox(bbox)
        h_label = self.emb_label(inputs["label"].long())
        x = self.enc_fc_in(torch.cat([h_bbox, h_label], dim=-1))
        x = torch.relu(x).permute(1, 0, 2)
        x = self.enc_transformer(x, padding_mask)
        return x[0]

BaseDecoder

Bases: Module

RALF autoregressive transformer decoder.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
455
456
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
class BaseDecoder(nn.Module):
    """RALF autoregressive transformer decoder."""

    def __init__(
        self,
        d_label: int,
        d_model: int,
        num_layers: int,
        nhead: int,
        pos_emb: str = "layout",
        dim_feedforward: int = 2048,
    ) -> None:
        super().__init__()
        if pos_emb != "layout":
            raise ValueError(
                "RALF converted checkpoints use layout positional encoding"
            )

        self.tie_weights = False
        self.transformer = nn.TransformerDecoder(
            decoder_layer=nn.TransformerDecoderLayer(
                d_model=d_model,
                nhead=nhead,
                batch_first=True,
                norm_first=True,
                dim_feedforward=dim_feedforward,
            ),
            num_layers=num_layers,
        )
        self.d_model = d_model
        self.emb = nn.Embedding(d_label, d_model)
        self.pos_emb = PositionalEncoding1d(d_model=d_model)
        self.head = nn.Sequential(
            nn.LayerNorm(d_model), nn.Linear(d_model, d_label, bias=False)
        )
        self.use_paramter_ablation = False

    def init_weight(self) -> None:
        for p in self.transformer.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)
        nn.init.normal_(self.emb.weight, mean=0.0, std=0.02)
        for module in self.head:
            if isinstance(module, nn.LayerNorm):
                nn.init.zeros_(module.bias)
                nn.init.ones_(module.weight)
            elif isinstance(module, nn.Linear):
                nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def forward(
        self,
        tgt: Int[torch.Tensor, "batch tokens"],
        memory: Float[torch.Tensor, "batch memory_tokens channels"],
        tgt_key_padding_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        is_causal: bool = False,
    ) -> Float[torch.Tensor, "batch tokens vocab"]:
        h = self.pos_emb(self.emb(tgt))
        if is_causal:
            tgt_mask = nn.Transformer.generate_square_subsequent_mask(h.size(1))
            h = self.transformer(
                h,
                memory,
                tgt_mask=tgt_mask.to(h.device),
                tgt_key_padding_mask=tgt_key_padding_mask,
            )
        else:
            h = self.transformer(h, memory, tgt_key_padding_mask=tgt_key_padding_mask)
        return self.head(h)

UserConstraintTransformerEncoder

Bases: Module

RALF encoder for task/user constraint tokens.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class UserConstraintTransformerEncoder(nn.Module):
    """RALF encoder for task/user constraint tokens."""

    def __init__(
        self,
        d_model: int,
        nhead: int,
        num_layers: int,
        d_label: int,
        dim_feedforward: int = 2048,
    ) -> None:
        super().__init__()
        self.encoder = nn.TransformerEncoder(
            encoder_layer=nn.TransformerEncoderLayer(
                d_model=d_model,
                nhead=nhead,
                batch_first=True,
                dropout=0.1,
                norm_first=True,
                dim_feedforward=dim_feedforward,
            ),
            num_layers=num_layers,
        )
        self.emb = nn.Embedding(d_label, d_model)
        nn.init.normal_(self.emb.weight, mean=0.0, std=0.02)
        self.pos_emb = PositionalEncoding1d(d_model=d_model)

    def init_weight(self) -> None:
        for p in self.encoder.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)

    def forward(
        self,
        src: Int[torch.Tensor, "batch tokens"],
        src_key_padding_mask: Bool[torch.Tensor, "batch tokens"],
        task_token: Int[torch.Tensor, "batch tokens"] | None,
    ) -> Float[torch.Tensor, "batch tokens channels"]:
        h = self.pos_emb(self.emb(src))
        h = self.encoder(src=h, src_key_padding_mask=src_key_padding_mask)
        if task_token is not None:
            h = h + self.emb(task_token)
        return h

RalfTokenizerView

Small tokenizer view matching the token ids needed by the model.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
class RalfTokenizerView:
    """Small tokenizer view matching the token ids needed by the model."""

    def __init__(self, config: RalfConfig) -> None:
        self.config = config
        id2label = cast(dict[int, str], config.id2label)
        self.label_names = [
            label
            for _idx, label in sorted(id2label.items(), key=lambda item: int(item[0]))
        ]
        self.var_order = list(config.var_order)
        self.special_tokens = list(config.special_tokens)
        self._label_feature = self
        self.names = self.label_names
        self.num_classes = len(self.label_names)
        self._special_token_name_to_id = {
            token: self.name_to_id(token) for token in self.special_tokens
        }

    @property
    def N_label(self) -> int:
        return self.num_classes

    @property
    def N_bbox_per_var(self) -> int:
        return self.config.num_bin

    @property
    def N_bbox(self) -> int:
        return self.config.num_bbox_tokens

    @property
    def N_sp_token(self) -> int:
        return len(self.special_tokens)

    @property
    def N_total(self) -> int:
        return self.config.vocab_size

    @property
    def max_seq_length(self) -> int:
        return self.config.max_seq_length

    @property
    def max_token_length(self) -> int:
        return self.config.max_token_length

    def name_to_id(self, name: str) -> int:
        return self.config.special_token_id(name)

RalfTaskPreprocessor

RALF task token preprocessor.

Source code in models/ralf/src/ralf/modeling_ralf.py
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
class RalfTaskPreprocessor:
    """RALF task token preprocessor."""

    def __init__(
        self,
        tokenizer: RalfTokenizerView,
        *,
        task: RalfTaskName,
        global_task_embedding: bool = False,
        relationship_table: RalfRelationshipTable | None = None,
        relation_size: int = 10,
    ) -> None:
        self.tokenizer = tokenizer
        self.global_task_embedding = global_task_embedding
        self.task_name = task
        self.relationship_table = (
            {
                str(key): random.sample(values, len(values))
                for key, values in relationship_table.items()
            }
            if relationship_table is not None
            else None
        )
        self.relation_size = int(relation_size)
        self._TASK = TASK_TOKEN_BY_TASK[task]
        self._VAR = PREPROCESSOR_VAR_BY_TASK.get(task, ())
        self.device = torch.device("cpu")
        tokens = (
            TASK_TOKEN_VOCABULARIES
            + SPECIAL_TASK_TOKENS
            + RELATIONSHIP_TOKENS
            + RELATIONSHIP_POSITION_TOKENS
            + RELATIONSHIP_SIZE_TOKENS
        )
        self._preprocess_token_name_to_id = {
            token: idx + self.tokenizer.N_total for idx, token in enumerate(tokens)
        }
        labelname_to_id = {
            name: self.tokenizer.names.index(name) for name in self.tokenizer.names
        }
        self._token_to_name_to_id = {
            **self.tokenizer._special_token_name_to_id,
            **self._preprocess_token_name_to_id,
            **labelname_to_id,
        }

    @property
    def TASK(self) -> RalfTaskTokenName:
        return self._TASK

    @property
    def N_total(self) -> int:
        return self.tokenizer.N_total + len(self._preprocess_token_name_to_id)

    def name_to_id(self, name: str) -> int:
        return self._token_to_name_to_id[name]

    def _relation_item_to_name(self, item: RalfRelationItem) -> str:
        name = getattr(item, "name", item)
        class_name = item.__class__.__name__
        if not isinstance(name, str):
            return str(name)
        if name == "UNKNOWN":
            return "unknown_size" if class_name == "RelSize" else "unknown_loc"
        relation_names = {
            "LEFT": "left",
            "TOP": "top",
            "RIGHT": "right",
            "BOTTOM": "bottom",
            "CENTER": "center",
            "SMALLER": "smaller",
            "EQUAL": "equal",
            "LARGER": "larger",
        }
        return relation_names.get(name, name)

    def _relation_item_to_id(self, item: RalfRelationItem) -> int:
        return self.name_to_id(self._relation_item_to_name(item))

    def get_token(self, name: str, batch_size: int) -> Int[torch.Tensor, "batch 1"]:
        return torch.full((batch_size, 1), self.name_to_id(name), device=self.device)

    def create_task_token(
        self, batch_size: int
    ) -> Int[torch.Tensor, "batch task_tokens"]:
        return torch.cat(
            [
                self.get_token(self.TASK, batch_size),
                self.get_token("end_of_task", batch_size),
            ],
            dim=-1,
        )

    def create_pad_mask(
        self, seq: Int[torch.Tensor, "batch tokens"]
    ) -> Bool[torch.Tensor, "batch tokens"]:
        return seq == self.name_to_id("pad")

    def _parse_seq_into_vars(
        self, seq: Int[torch.Tensor, "batch tokens"]
    ) -> dict[str, Int[torch.Tensor, "batch elements"]]:
        seq = seq.clone()
        seq[seq == self.name_to_id("eos")] = self.name_to_id("pad")
        seq = seq[:, 1:]
        seq = seq.reshape(seq.size(0), -1, len(self.tokenizer.var_order))
        return {key: seq[..., idx] for idx, key in enumerate(self.tokenizer.var_order)}

    def _shuffle_seq_vars(
        self, seq_vars: dict[str, Int[torch.Tensor, "batch elements"]]
    ) -> dict[str, Int[torch.Tensor, "batch elements"]]:
        label = seq_vars["label"]
        non_padding_counts = (label != self.name_to_id("pad")).sum(dim=1)
        shuffled = {key: value.clone() for key, value in seq_vars.items()}
        for batch_idx, count in enumerate(non_padding_counts.tolist()):
            if count <= 1:
                continue
            indexes = torch.randperm(count, device=label.device)
            for key, value in seq_vars.items():
                shuffled[key][batch_idx, :count] = value[batch_idx, indexes]
        return shuffled

    def _valid_element_mask(
        self, seq_vars: Mapping[str, Int[torch.Tensor, "batch elements"]]
    ) -> Bool[torch.Tensor, "batch elements"]:
        label = seq_vars["label"]
        return (label != self.name_to_id("pad")) & (label != self.name_to_id("eos"))

    def _geo_sequence(
        self, inputs: RalfConditionalInputs
    ) -> Int[torch.Tensor, "batch tokens"]:
        if inputs.seq is None:
            raise ValueError(f"condition_type={self.task_name!r} requires labels")

        seq = inputs.seq
        if self.task_name == "partial" and inputs.mask is not None:
            seq = seq.clone()
            seq[~inputs.mask.bool()] = self.name_to_id("pad")
        seq_vars = self._parse_seq_into_vars(seq)
        if self.task_name == "relation":
            _ = self._shuffle_seq_vars(seq_vars)
            seq_vars = self._shuffle_seq_vars(seq_vars)
        elif self.task_name == "c":
            seq_vars = self._shuffle_seq_vars(seq_vars)
        valid = (
            self._valid_element_mask(seq_vars)
            if inputs.element_mask is None
            else inputs.element_mask[:, : seq_vars["label"].size(1)].bool()
        )
        if self.task_name == "partial":
            valid = torch.zeros_like(valid)
            if valid.size(1) > 0:
                valid[:, 0] = True
        max_valid = int(valid.sum(dim=1).max().item()) if valid.numel() else 0
        if max_valid == 0:
            return self.get_token("pad", inputs.image.size(0))
        pieces: list[Int[torch.Tensor, "batch token_piece"]] = []
        sep = self.get_token("sep", inputs.image.size(0))
        for element_idx in range(max_valid):
            for key in self._VAR:
                values = seq_vars[key][:, element_idx : element_idx + 1]
                values = torch.where(
                    valid[:, element_idx : element_idx + 1],
                    values,
                    self.get_token("pad", inputs.image.size(0)),
                )
                pieces.append(values)
            if element_idx != max_valid - 1:
                pieces.append(sep)
        return torch.cat(pieces, dim=1)

    def _relation_ids(
        self,
        ids: Int[torch.Tensor, "batch"] | Sequence[int | str] | int | str | None,
        batch_size: int,
    ) -> list[str]:
        if ids is None:
            return [""] * batch_size
        if isinstance(ids, Tensor):
            return [str(item) for item in ids.detach().cpu().tolist()]
        if isinstance(ids, (list, tuple)):
            return [str(item) for item in ids]
        return [str(ids)] * batch_size

    def _relation_sequence(
        self,
        inputs: RalfConditionalInputs,
        label_sequence: Int[torch.Tensor, "batch tokens"],
    ) -> Int[torch.Tensor, "batch relation_tokens"]:
        if self.relationship_table is None:
            return label_sequence
        batch = label_sequence.size(0)
        label_mask = self.create_pad_mask(label_sequence)
        label_sequence = label_sequence.clone()
        if not self.global_task_embedding:
            label_sequence[:, 1] = self.get_token(self.TASK, batch)[:, 0]
        label_sequence[label_sequence == self.name_to_id("eos")] = self.name_to_id(
            "relation_sep"
        )

        outputs = []
        max_length = 0
        for batch_idx, item_id in enumerate(self._relation_ids(inputs.id, batch)):
            seq = label_sequence[batch_idx][~label_mask[batch_idx]]
            relations = self.relationship_table.get(item_id, [])
            if not relations:
                seq = torch.cat([seq, self.get_token("eos", 1)[0]], dim=0)
                outputs.append(seq)
                max_length = max(max_length, seq.size(0))
                continue
            sample_size = max(len(relations) * self.relation_size // 100, 1)
            sampled = random.sample(relations, sample_size)
            relation_tokenized = torch.tensor(
                [
                    [self._relation_item_to_id(element) for element in relation]
                    for relation in sampled
                ],
                dtype=torch.long,
                device=self.device,
            )
            sep = self.get_token("sep", relation_tokenized.size(0))
            relation_with_sep = torch.cat([relation_tokenized, sep], dim=1).view(-1)
            relation_with_sep[-1] = self.name_to_id("eos")
            seq = torch.cat([seq, relation_with_sep], dim=0)
            outputs.append(seq)
            max_length = max(max_length, seq.size(0))
        out = torch.full(
            (batch, max_length),
            fill_value=self.name_to_id("pad"),
            dtype=torch.long,
            device=self.device,
        )
        for batch_idx, seq in enumerate(outputs):
            out[batch_idx, : seq.size(0)] = seq
        return out

    def __call__(
        self, inputs: RalfConditionalInputs
    ) -> dict[str, Shaped[torch.Tensor, ...]]:
        batch = inputs.image.size(0)
        self.device = inputs.image.device
        bos = self.get_token("bos", batch)
        eos = self.get_token("eos", batch)
        body = (
            torch.empty(batch, 0, dtype=torch.long, device=self.device)
            if self.task_name == "uncond"
            else self._geo_sequence(inputs)
        )
        if self.global_task_embedding:
            seq = torch.cat([bos, body, eos], dim=-1)
        else:
            seq = torch.cat([bos, self.create_task_token(batch), body, eos], dim=-1)
        if self.task_name == "relation":
            seq = self._relation_sequence(inputs, seq)
        return {"seq": seq.long(), "pad_mask": self.create_pad_mask(seq)}

RalfConditionalInputs dataclass

Model-side generation inputs.

Source code in models/ralf/src/ralf/modeling_ralf.py
852
853
854
855
856
857
858
859
860
861
862
@dataclass
class RalfConditionalInputs:
    """Model-side generation inputs."""

    image: Float[torch.Tensor, "batch channels height width"]
    retrieved: dict[str, Shaped[torch.Tensor, ...]]
    seq: Int[torch.Tensor, "batch tokens"] | None = None
    mask: Bool[torch.Tensor, "batch tokens"] | None = None
    element_mask: Bool[torch.Tensor, "batch elements"] | None = None
    task: RalfTaskName | None = "uncond"
    id: Int[torch.Tensor, "batch"] | Sequence[int | str] | int | str | None = None

RalfForConditionalLayoutGeneration

Bases: PreTrainedModel

Standalone PreTrainedModel for RALF autoregressive decoding.

Source code in models/ralf/src/ralf/modeling_ralf.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
class RalfForConditionalLayoutGeneration(PreTrainedModel):
    """Standalone `PreTrainedModel` for RALF autoregressive decoding."""

    config_class = RalfConfig
    base_model_prefix = "ralf"
    main_input_name = "input_ids"
    _tied_weights_keys: dict[str, str] = {}

    flag_img: Int[torch.Tensor, "1"]
    flag_user_const: Int[torch.Tensor, "1"]

    def __init__(self, config: RalfConfig) -> None:
        """Initialize a local module tree matching original RALF checkpoint keys."""
        super().__init__(config)
        self.tokenizer = RalfTokenizerView(config)
        self.dataset_name = config.dataset_name
        self.d_model = config.d_model
        self.max_seq_length = config.max_seq_length

        self.use_reference_image = config.use_reference_image
        self.layout_backbone = config.layout_backbone
        self.top_k = config.top_k
        self.weight_init = True

        self.retrieval_backbone = config.retrieval_backbone
        self.random_retrieval = False
        self.saliency_k = str(config.saliency_k)

        self.num_layers = config.encoder_layers
        self.nhead = config.num_attention_heads
        self.dropout = config.dropout

        self.encoder = ResnetFeatureExtractor(
            backbone="resnet50", d_model=config.d_model, head="transformer"
        )
        self.pos_emb_2d = PositionEmbeddingSine(config.d_model, normalize=True)
        self.dim_feedforward = 4 * config.d_model
        self.transformer_encoder = nn.TransformerEncoder(
            encoder_layer=nn.TransformerEncoderLayer(
                d_model=config.d_model,
                nhead=config.num_attention_heads,
                batch_first=True,
                dropout=config.dropout,
                norm_first=True,
                dim_feedforward=self.dim_feedforward,
            ),
            num_layers=config.encoder_layers,
        )
        self.decoder = BaseDecoder(
            d_label=self.tokenizer.N_total,
            d_model=config.decoder_d_model,
            num_layers=config.decoder_layers,
            nhead=config.num_attention_heads,
            pos_emb="layout",
            dim_feedforward=self.dim_feedforward,
        )
        self.loss_fn_ce = nn.CrossEntropyLoss(
            label_smoothing=0.1, ignore_index=self.tokenizer.name_to_id("pad")
        )
        self.layout_encoer = FIDNetFeatureExtractor(
            num_label=self.tokenizer.N_label,
            d_model=256,
            nhead=4,
            num_layers=4,
            max_bbox=config.max_seq_length,
        )
        self.layout_encoer.enc_transformer.token.requires_grad = False
        for parameter in self.layout_encoer.parameters():
            parameter.requires_grad = False
        self.pos_emb_1d = PositionalEncoding1d(
            d_model=config.d_model,
            max_len=5000 if not config.use_reference_image else 10000,
        )
        self.layout_adapter = FeedForward(
            dim=256, hidden_dim=4 * config.d_model, output_dim=config.d_model
        )
        self.head = FeedForward(dim=config.d_model, hidden_dim=4 * config.d_model)
        self.auxilary_task = self._canonical_to_task_name(config.task)
        self.use_multitask = config.use_multitask
        self.global_task_embedding = config.global_task_embedding
        self.preprocessor = RalfTaskPreprocessor(
            tokenizer=self.tokenizer,
            task=self.auxilary_task,
            global_task_embedding=config.global_task_embedding,
        )
        self.user_const_encoder = UserConstraintTransformerEncoder(
            d_model=config.d_model,
            nhead=config.num_attention_heads,
            num_layers=config.encoder_layers,
            d_label=self.preprocessor.N_total,
            dim_feedforward=self.dim_feedforward,
        )
        self.use_flag_embedding = config.use_flag_embedding
        if self.use_flag_embedding:
            self.task_emb = nn.Embedding(2, 1)
            nn.init.normal_(self.task_emb.weight, mean=0.0, std=0.02)
            self.register_buffer("flag_img", torch.zeros(1).long())
            self.register_buffer("flag_user_const", torch.ones(1).long())
        self.attn = Attention(
            config.d_model, config.d_model, heads=8, dim_head=64, dropout=0.0
        )
        self.all_tied_weights_keys = dict(self._tied_weights_keys)

    @staticmethod
    def _canonical_to_task_name(task: RalfConfigTaskName | str) -> RalfTaskName:
        if task not in TASK_BY_CONDITION:
            raise ValueError(f"Unsupported RALF task or condition: {task}")

        return TASK_BY_CONDITION[cast(RalfConfigTaskName, task)]

    def _default_retrieved(
        self, batch_size: int, device: torch.device, dtype: torch.dtype
    ) -> dict[str, Shaped[torch.Tensor, ...]]:
        shape = (batch_size, self.config.top_k, self.config.max_seq_length)
        image = torch.zeros(
            batch_size, self.config.top_k, 4, 64, 64, device=device, dtype=dtype
        )
        return {
            "image": image,
            "center_x": torch.zeros(shape, device=device, dtype=dtype),
            "center_y": torch.zeros(shape, device=device, dtype=dtype),
            "width": torch.zeros(shape, device=device, dtype=dtype),
            "height": torch.zeros(shape, device=device, dtype=dtype),
            "label": torch.zeros(shape, device=device, dtype=torch.long),
            "mask": torch.zeros(shape, device=device, dtype=torch.bool),
        }

    def _encode_into_memory(
        self,
        inputs: Mapping[
            str, Shaped[torch.Tensor, ...] | Mapping[str, Shaped[torch.Tensor, ...]]
        ],
    ) -> dict[str, Float[torch.Tensor, "batch memory_tokens channels"]]:
        image = cast(Tensor, inputs["image"])
        retrieved = cast(Mapping[str, Shaped[torch.Tensor, "..."]], inputs["retrieved"])
        input_img_feature = self.encoder(image)
        input_img_feature = self.pos_emb_2d(input_img_feature)
        image_memory = self.transformer_encoder(input_img_feature)
        ref_layouts = _extract_retrieved_features(
            retrieved_samples=retrieved,
            top_k=self.top_k,
            layout_encoder=self.layout_encoer,
            layout_adapter=self.layout_adapter,
            pos_emb_1d=self.pos_emb_1d,
        )
        memory_ca = self.attn(image_memory, ref_layouts)
        img_retrieved_layout_memory = self.head(
            torch.cat([image_memory, memory_ca, ref_layouts], dim=1)
        )
        if self.global_task_embedding:
            task_token = self.preprocessor.get_token(
                self.preprocessor.TASK, img_retrieved_layout_memory.size(0)
            ).type_as(cast(Tensor, inputs["seq_layout_const"]))
        else:
            task_token = None
        user_const_feature = self.user_const_encoder(
            src=cast(Tensor, inputs["seq_layout_const"]),
            src_key_padding_mask=cast(Tensor, inputs["seq_layout_const_pad_mask"]),
            task_token=task_token,
        )
        if self.use_flag_embedding:
            img_retrieved_layout_memory = img_retrieved_layout_memory + self.task_emb(
                self.flag_img
            )
            user_const_feature = user_const_feature + self.task_emb(
                self.flag_user_const
            )
        return {
            "memory": torch.cat(
                [img_retrieved_layout_memory, user_const_feature], dim=1
            )
        }

    def _prepare_conditional_inputs(
        self,
        *,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None,
        retrieved: RalfRetrievedBatch | None,
        batch_size: int,
        condition_type: RalfConfigTaskName | None = None,
        constraint_input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
        constraint_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
        relationship_table: RalfRelationshipTable | None = None,
        sample_ids: Int[torch.Tensor, "batch"]
        | Sequence[int | str]
        | int
        | str
        | None = None,
    ) -> dict[str, Shaped[torch.Tensor, ...] | Mapping[str, Shaped[torch.Tensor, ...]]]:
        device = next(self.parameters()).device
        dtype = next(self.parameters()).dtype
        if pixel_values is None:
            pixel_values = torch.zeros(
                batch_size, 3, 64, 64, device=device, dtype=dtype
            )
        if saliency is None:
            saliency = torch.zeros(
                pixel_values.size(0),
                1,
                pixel_values.size(2),
                pixel_values.size(3),
                device=pixel_values.device,
                dtype=pixel_values.dtype,
            )
        if pixel_values.size(-1) < 64 or pixel_values.size(-2) < 64:
            pixel_values = F.interpolate(
                pixel_values, size=(64, 64), mode="bilinear", align_corners=False
            )
            saliency = F.interpolate(
                saliency, size=(64, 64), mode="bilinear", align_corners=False
            )
        if pixel_values.size(0) == 1 and batch_size > 1:
            pixel_values = pixel_values.expand(batch_size, -1, -1, -1)
            saliency = saliency.expand(batch_size, -1, -1, -1)
        image = torch.cat([pixel_values, saliency], dim=1).to(
            device=device, dtype=dtype
        )
        retrieved_dict = (
            self._default_retrieved(image.size(0), device, dtype)
            if retrieved is None
            else {
                key: value.to(device=device, dtype=dtype)
                if value.is_floating_point()
                else value.to(device=device)
                for key, value in retrieved_batch_to_model_inputs(retrieved).items()
            }
        )
        if retrieved_dict["image"].size(2) == 3:
            retrieved_dict["image"] = torch.cat(
                [retrieved_dict["image"], retrieved_dict["saliency"]], dim=2
            )
        task = self._canonical_to_task_name(condition_type or self.auxilary_task)
        preprocessor = (
            self.preprocessor
            if task == self.auxilary_task and relationship_table is None
            else RalfTaskPreprocessor(
                tokenizer=self.tokenizer,
                task=task,
                global_task_embedding=self.global_task_embedding,
                relationship_table=relationship_table if task == "relation" else None,
                relation_size=self.config.relation_size,
            )
        )
        cond = RalfConditionalInputs(
            image=image,
            retrieved=retrieved_dict,
            seq=constraint_input_ids,
            mask=constraint_mask,
            element_mask=constraint_element_mask,
            task=task,
            id=sample_ids,
        )
        seq_constraints = preprocessor(cond)
        return {
            "image": image,
            "retrieved": retrieved_dict,
            "seq_layout_const": seq_constraints["seq"],
            "seq_layout_const_pad_mask": seq_constraints["pad_mask"],
        }

    def _prepare_unconditional_inputs(
        self,
        *,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None,
        retrieved: RalfRetrievedBatch | None,
        batch_size: int,
    ) -> dict[str, Shaped[torch.Tensor, ...] | Mapping[str, Shaped[torch.Tensor, ...]]]:
        return self._prepare_conditional_inputs(
            pixel_values=pixel_values,
            saliency=saliency,
            retrieved=retrieved,
            batch_size=batch_size,
            condition_type="uncond",
        )

    def forward(
        self,
        input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None = None,
        attention_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        labels: Int[torch.Tensor, "batch tokens"] | None = None,
        retrieved: RalfRetrievedBatch | None = None,
        condition_type: RalfConfigTaskName | None = None,
        constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
        return_dict: bool | None = None,
        **kwargs: str | float | bool | None,
    ) -> CausalLMOutput | tuple[Float[torch.Tensor, ...], ...]:
        """Run teacher-forced token prediction using the local RALF port."""
        relationship_table = cast(
            RalfRelationshipTable | None, kwargs.get("relationship_table")
        )
        sample_ids = cast(
            Int[torch.Tensor, "batch"] | Sequence[int | str] | int | str | None,
            kwargs.get("sample_ids"),
        )
        if input_ids is None:
            raise ValueError("input_ids is required")

        encoder_inputs = self._prepare_conditional_inputs(
            pixel_values=pixel_values,
            saliency=saliency,
            retrieved=retrieved,
            batch_size=input_ids.size(0),
            condition_type=condition_type,
            constraint_input_ids=input_ids,
            constraint_mask=attention_mask,
            constraint_element_mask=constraint_element_mask,
            relationship_table=relationship_table,
            sample_ids=sample_ids,
        )
        encoded_feat = self._encode_into_memory(encoder_inputs)
        logits = self.decoder(
            tgt=input_ids,
            tgt_key_padding_mask=None
            if attention_mask is None
            else ~attention_mask.bool(),
            is_causal=True,
            **encoded_feat,
        )
        loss = None
        if labels is not None:
            targets = labels.clone()
            targets[targets == self.config.pad_token_id] = -100
            loss = F.cross_entropy(
                logits.reshape(-1, logits.size(-1)),
                targets.reshape(-1),
                ignore_index=-100,
            )
        if return_dict is False:
            return (logits,) if loss is None else (loss, logits)
        return CausalLMOutput(loss=cast(torch.FloatTensor | None, loss), logits=logits)

    @torch.no_grad()
    def _generate_sequences(
        self,
        input_ids: Int[torch.Tensor, "batch tokens"],
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
        saliency: Float[torch.Tensor, "batch 1 height width"] | None = None,
        attention_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        *,
        max_length: int | None = None,
        temperature: float = 1.0,
        top_k: int | None = None,
        generator: torch.Generator | None = None,
        token_mask: Bool[torch.Tensor, "tokens vocab"] | None = None,
        retrieved: RalfRetrievedBatch | None = None,
        condition_type: RalfConfigTaskName | None = None,
        constraint_input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
        constraint_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
        constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
        relationship_table: RalfRelationshipTable | None = None,
        sample_ids: Int[torch.Tensor, "batch"]
        | Sequence[int | str]
        | int
        | str
        | None = None,
    ) -> Int[torch.Tensor, "batch tokens"]:
        """Run the RALF autoregressive token loop used by `RalfPipeline`."""
        _ = attention_mask
        was_training = self.training
        self.eval()
        task = self._canonical_to_task_name(condition_type or self.auxilary_task)
        generated = input_ids[:, :1].clone()
        start_step = 0
        if task == "partial":
            condition_seq = (
                constraint_input_ids if constraint_input_ids is not None else input_ids
            )
            prefix = condition_seq[:, 1 : 1 + len(self.config.var_order)]
            generated = torch.cat([generated, prefix.to(generated.device)], dim=1)
            start_step = len(self.config.var_order)
        max_length = max_length or self.config.max_token_length
        encoder_inputs = self._prepare_conditional_inputs(
            pixel_values=pixel_values,
            saliency=saliency,
            retrieved=retrieved,
            batch_size=input_ids.size(0),
            condition_type=task,
            constraint_input_ids=constraint_input_ids,
            constraint_mask=constraint_mask,
            constraint_element_mask=constraint_element_mask,
            relationship_table=relationship_table,
            sample_ids=sample_ids,
        )
        encoded_feat = self._encode_into_memory(encoder_inputs)
        try:
            for step in range(start_step, max_length):
                logits = self.decoder(
                    tgt=generated,
                    tgt_key_padding_mask=generated.eq(self.config.pad_token_id),
                    is_causal=True,
                    **encoded_feat,
                )
                next_logits = logits[:, step : step + 1]
                next_logits = rearrange(next_logits, "b 1 c -> b c") / temperature
                if token_mask is not None and step < token_mask.size(0):
                    next_logits = next_logits.masked_fill(
                        ~token_mask[step].to(next_logits.device), -math.inf
                    )
                next_logits = _apply_decode_space_restriction(
                    task=task,
                    step=step,
                    condition=constraint_input_ids,
                    logits=next_logits,
                    pad_id=self.config.pad_token_id,
                    eos_id=self.config.eos_token_id,
                    max_length=self.config.max_token_length,
                )
                if top_k is not None and top_k > 0 and top_k < next_logits.size(-1):
                    values = torch.topk(next_logits, top_k).values
                    next_logits = next_logits.masked_fill(
                        next_logits < values[:, [-1]], -math.inf
                    )
                probs = F.softmax(next_logits, dim=-1)
                next_token = torch.multinomial(
                    probs, num_samples=1, generator=generator
                )
                generated = torch.cat([generated, next_token], dim=1)
        finally:
            if was_training:
                self.train()
        return generated

__init__

__init__(config: RalfConfig) -> None

Initialize a local module tree matching original RALF checkpoint keys.

Source code in models/ralf/src/ralf/modeling_ralf.py
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def __init__(self, config: RalfConfig) -> None:
    """Initialize a local module tree matching original RALF checkpoint keys."""
    super().__init__(config)
    self.tokenizer = RalfTokenizerView(config)
    self.dataset_name = config.dataset_name
    self.d_model = config.d_model
    self.max_seq_length = config.max_seq_length

    self.use_reference_image = config.use_reference_image
    self.layout_backbone = config.layout_backbone
    self.top_k = config.top_k
    self.weight_init = True

    self.retrieval_backbone = config.retrieval_backbone
    self.random_retrieval = False
    self.saliency_k = str(config.saliency_k)

    self.num_layers = config.encoder_layers
    self.nhead = config.num_attention_heads
    self.dropout = config.dropout

    self.encoder = ResnetFeatureExtractor(
        backbone="resnet50", d_model=config.d_model, head="transformer"
    )
    self.pos_emb_2d = PositionEmbeddingSine(config.d_model, normalize=True)
    self.dim_feedforward = 4 * config.d_model
    self.transformer_encoder = nn.TransformerEncoder(
        encoder_layer=nn.TransformerEncoderLayer(
            d_model=config.d_model,
            nhead=config.num_attention_heads,
            batch_first=True,
            dropout=config.dropout,
            norm_first=True,
            dim_feedforward=self.dim_feedforward,
        ),
        num_layers=config.encoder_layers,
    )
    self.decoder = BaseDecoder(
        d_label=self.tokenizer.N_total,
        d_model=config.decoder_d_model,
        num_layers=config.decoder_layers,
        nhead=config.num_attention_heads,
        pos_emb="layout",
        dim_feedforward=self.dim_feedforward,
    )
    self.loss_fn_ce = nn.CrossEntropyLoss(
        label_smoothing=0.1, ignore_index=self.tokenizer.name_to_id("pad")
    )
    self.layout_encoer = FIDNetFeatureExtractor(
        num_label=self.tokenizer.N_label,
        d_model=256,
        nhead=4,
        num_layers=4,
        max_bbox=config.max_seq_length,
    )
    self.layout_encoer.enc_transformer.token.requires_grad = False
    for parameter in self.layout_encoer.parameters():
        parameter.requires_grad = False
    self.pos_emb_1d = PositionalEncoding1d(
        d_model=config.d_model,
        max_len=5000 if not config.use_reference_image else 10000,
    )
    self.layout_adapter = FeedForward(
        dim=256, hidden_dim=4 * config.d_model, output_dim=config.d_model
    )
    self.head = FeedForward(dim=config.d_model, hidden_dim=4 * config.d_model)
    self.auxilary_task = self._canonical_to_task_name(config.task)
    self.use_multitask = config.use_multitask
    self.global_task_embedding = config.global_task_embedding
    self.preprocessor = RalfTaskPreprocessor(
        tokenizer=self.tokenizer,
        task=self.auxilary_task,
        global_task_embedding=config.global_task_embedding,
    )
    self.user_const_encoder = UserConstraintTransformerEncoder(
        d_model=config.d_model,
        nhead=config.num_attention_heads,
        num_layers=config.encoder_layers,
        d_label=self.preprocessor.N_total,
        dim_feedforward=self.dim_feedforward,
    )
    self.use_flag_embedding = config.use_flag_embedding
    if self.use_flag_embedding:
        self.task_emb = nn.Embedding(2, 1)
        nn.init.normal_(self.task_emb.weight, mean=0.0, std=0.02)
        self.register_buffer("flag_img", torch.zeros(1).long())
        self.register_buffer("flag_user_const", torch.ones(1).long())
    self.attn = Attention(
        config.d_model, config.d_model, heads=8, dim_head=64, dropout=0.0
    )
    self.all_tied_weights_keys = dict(self._tied_weights_keys)

forward

forward(
    input_ids: Int[Tensor, "batch tokens"] | None = None,
    pixel_values: Float[
        Tensor, "batch channels height width"
    ]
    | None = None,
    saliency: Float[Tensor, "batch 1 height width"]
    | None = None,
    attention_mask: Bool[Tensor, "batch tokens"]
    | None = None,
    labels: Int[Tensor, "batch tokens"] | None = None,
    retrieved: RalfRetrievedBatch | None = None,
    condition_type: RalfConfigTaskName | None = None,
    constraint_element_mask: Bool[Tensor, "batch elements"]
    | None = None,
    return_dict: bool | None = None,
    **kwargs: str | float | bool | None,
) -> CausalLMOutput | tuple[Float[torch.Tensor, ...], ...]

Run teacher-forced token prediction using the local RALF port.

Source code in models/ralf/src/ralf/modeling_ralf.py
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
def forward(
    self,
    input_ids: Int[torch.Tensor, "batch tokens"] | None = None,
    pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
    saliency: Float[torch.Tensor, "batch 1 height width"] | None = None,
    attention_mask: Bool[torch.Tensor, "batch tokens"] | None = None,
    labels: Int[torch.Tensor, "batch tokens"] | None = None,
    retrieved: RalfRetrievedBatch | None = None,
    condition_type: RalfConfigTaskName | None = None,
    constraint_element_mask: Bool[torch.Tensor, "batch elements"] | None = None,
    return_dict: bool | None = None,
    **kwargs: str | float | bool | None,
) -> CausalLMOutput | tuple[Float[torch.Tensor, ...], ...]:
    """Run teacher-forced token prediction using the local RALF port."""
    relationship_table = cast(
        RalfRelationshipTable | None, kwargs.get("relationship_table")
    )
    sample_ids = cast(
        Int[torch.Tensor, "batch"] | Sequence[int | str] | int | str | None,
        kwargs.get("sample_ids"),
    )
    if input_ids is None:
        raise ValueError("input_ids is required")

    encoder_inputs = self._prepare_conditional_inputs(
        pixel_values=pixel_values,
        saliency=saliency,
        retrieved=retrieved,
        batch_size=input_ids.size(0),
        condition_type=condition_type,
        constraint_input_ids=input_ids,
        constraint_mask=attention_mask,
        constraint_element_mask=constraint_element_mask,
        relationship_table=relationship_table,
        sample_ids=sample_ids,
    )
    encoded_feat = self._encode_into_memory(encoder_inputs)
    logits = self.decoder(
        tgt=input_ids,
        tgt_key_padding_mask=None
        if attention_mask is None
        else ~attention_mask.bool(),
        is_causal=True,
        **encoded_feat,
    )
    loss = None
    if labels is not None:
        targets = labels.clone()
        targets[targets == self.config.pad_token_id] = -100
        loss = F.cross_entropy(
            logits.reshape(-1, logits.size(-1)),
            targets.reshape(-1),
            ignore_index=-100,
        )
    if return_dict is False:
        return (logits,) if loss is None else (loss, logits)
    return CausalLMOutput(loss=cast(torch.FloatTensor | None, loss), logits=logits)

pipeline_ralf

Pipeline wrapper for RALF layout generation.

RalfPipelineComponent

Bases: Protocol

Runtime-checkable loaded pipeline component marker.

Source code in models/ralf/src/ralf/pipeline_ralf.py
37
38
39
@runtime_checkable
class RalfPipelineComponent(Protocol):
    """Runtime-checkable loaded pipeline component marker."""

RalfPipeline

Bases: LayoutGenerationPipeline

Compose a RALF model and processor for content-aware retrieval generation.

Source code in models/ralf/src/ralf/pipeline_ralf.py
 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
class RalfPipeline(LayoutGenerationPipeline):
    """Compose a RALF model and processor for content-aware retrieval generation."""

    config_class: ClassVar[type[PretrainedConfig]] = RalfConfig
    component_specs: ClassVar[dict[str, PipelineComponentSpec]] = {
        "model": PipelineComponentSpec(
            attribute_name="model",
            loader=_load_model_component,
            marker_file="config.json",
        ),
        "processor": PipelineComponentSpec(
            attribute_name="processor",
            loader=_load_processor_component,
            marker_file="processor_config.json",
            save_with_is_main_process=False,
        ),
    }

    config: RalfConfig
    model: RalfForConditionalLayoutGeneration
    processor: RalfProcessor

    def __init__(
        self,
        model: RalfForConditionalLayoutGeneration,
        processor: RalfProcessor | None = None,
        config: RalfConfig | None = None,
    ) -> None:
        """Initialize the RALF pipeline."""
        super().__init__(config or model.config)
        self.config = config or model.config
        self.model = model
        self.processor = processor or RalfProcessor.from_config(self.config)

    @classmethod
    def _from_pretrained_components(
        cls,
        *,
        config: PretrainedConfig,
        components: Mapping[str, RalfPipelineComponent | None],
    ) -> "RalfPipeline":
        """Build a pipeline from checkpoint components."""
        return cls(
            config=cast(RalfConfig, config),
            model=cast(RalfForConditionalLayoutGeneration, components["model"]),
            processor=cast(RalfProcessor, components["processor"]),
        )

    @torch.no_grad()
    def __call__(  # ty: ignore[invalid-method-override]
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        saliency: ImageInput | Sequence[ImageInput] | None = None,
        batch_size: int = 1,
        seed: int | None = None,
        generator: torch.Generator | None = None,
        condition_type: ConditionType | str = ConditionType.unconditional,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[bool]
        | Sequence[Sequence[bool]]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        retrieved_layouts: Mapping[
            str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
        ]
        | None = None,
        retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
        retrieved_saliency: RalfSequenceInput
        | Shaped[torch.Tensor, "..."]
        | None = None,
        retrieved_indexes: Int[torch.Tensor, "batch candidates"]
        | Sequence[Sequence[int]]
        | None = None,
        retrieval: Mapping[
            str,
            RalfRetrievalValue
            | Shaped[torch.Tensor, "..."]
            | Mapping[str, Shaped[torch.Tensor, "..."]],
        ]
        | None = None,
        retrieval_table: RalfRetrievalTable | None = None,
        query_ids: Sequence[int | str] | None = None,
        relations: RalfRelationshipTable | None = None,
        num_inference_steps: int | None = None,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        return_intermediates: bool = False,
        temperature: float = 1.0,
        top_k: int | None = None,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Shaped[torch.Tensor, "..."]
            | dict[int, str]
            | Mapping[str, Shaped[torch.Tensor, "..."]]
            | None,
        ]
    ):
        """Generate layouts through the RALF public interface.

        Args:
            images: Poster/content images. When omitted, the pipeline uses a
                zero image for smoke/debug calls; converted checkpoints were
                trained with real content inputs.
            saliency: Optional saliency maps.
            batch_size: Batch size when images are absent.
            seed: Convenience seed used only when `generator` is absent.
            generator: PyTorch generator; takes precedence over `seed`.
            condition_type: Canonical condition type or alias.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Optional requested element counts.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size for pixel boxes.
            retrieved_layouts: Explicit retrieved layouts. When no retrieval data is
                supplied, the model receives zero retrieval memory for smoke/debug
                calls rather than paper-equivalent retrieved examples.
            retrieved_images: Explicit retrieved images.
            retrieved_saliency: Explicit retrieved saliency maps.
            retrieved_indexes: Explicit retrieved indexes.
            retrieval: Canonical v2 retrieval container.
            retrieval_table: Optional model-side retrieval table.
            query_ids: Query ids used for table lookup when explicit examples are absent.
            relations: Optional relation constraints.
            num_inference_steps: Reserved v1 argument.
            output_type: `dataclass` or `dict`.
            return_intermediates: Whether to return retrieval debug metadata.
            temperature: Sampling temperature.
            top_k: Optional top-k sampling limit.

        Returns:
            LayoutGenerationOutput or dictionary.
        """
        _ = (num_elements, num_inference_steps)
        condition = normalize_condition_type(condition_type)
        if condition not in SUPPORTED_GENERATION_CONDITIONS:
            raise NotImplementedError(
                "This RALF port currently supports unconditional, label, "
                "label_size, completion, refinement, relation, retrieval, and "
                "content_image; "
                f"got {condition}"
            )

        encoded = self.processor(
            images=images,
            saliency=saliency,
            condition_type=condition,
            labels=labels,
            bbox=bbox,
            mask=mask,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
            retrieved_layouts=retrieved_layouts,
            retrieved_images=retrieved_images,
            retrieved_saliency=retrieved_saliency,
            retrieved_indexes=retrieved_indexes,
            retrieval=retrieval,
            batch_size=batch_size,
        )
        model_device = next(self.model.parameters()).device
        generation_generator = self.prepare_generator(
            generator=generator,
            seed=seed,
            device=model_device,
        )
        intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]] = {}
        if "retrieval" in encoded:
            retrieval_batch = encoded["retrieval"]
            if retrieval_batch.indexes is not None:
                intermediates["retrieval"] = {"indexes": retrieval_batch.indexes}
        elif retrieval_table is not None and query_ids is not None:
            intermediates["retrieval"] = {"indexes": retrieval_table.lookup(query_ids)}
        sequences = self.model._generate_sequences(
            encoded["input_ids"].to(model_device),
            pixel_values=encoded["pixel_values"].to(model_device),
            saliency=encoded["saliency"].to(model_device),
            attention_mask=encoded["attention_mask"].to(model_device),
            max_length=self.config.max_token_length,
            temperature=temperature,
            top_k=top_k,
            generator=generation_generator,
            token_mask=self.processor.layout_tokenizer.token_mask(model_device),
            retrieved=encoded.get("retrieval"),
            condition_type=cast(RalfConfigTaskName, str(condition)),
            constraint_input_ids=encoded["input_ids"].to(model_device),
            constraint_mask=encoded["attention_mask"].to(model_device),
            constraint_element_mask=encoded["constraint_mask"].to(model_device),
            relationship_table=relations,
            sample_ids=query_ids,
        )
        return self.processor.post_process_layouts(
            sequences.cpu(),
            output_type=output_type,
            intermediates=intermediates if return_intermediates else None,
        )

    generate = __call__

__init__

__init__(
    model: RalfForConditionalLayoutGeneration,
    processor: RalfProcessor | None = None,
    config: RalfConfig | None = None,
) -> None

Initialize the RALF pipeline.

Source code in models/ralf/src/ralf/pipeline_ralf.py
112
113
114
115
116
117
118
119
120
121
122
def __init__(
    self,
    model: RalfForConditionalLayoutGeneration,
    processor: RalfProcessor | None = None,
    config: RalfConfig | None = None,
) -> None:
    """Initialize the RALF pipeline."""
    super().__init__(config or model.config)
    self.config = config or model.config
    self.model = model
    self.processor = processor or RalfProcessor.from_config(self.config)

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput
    | Sequence[ImageInput]
    | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: Generator | None = None,
    condition_type: ConditionType
    | str = ConditionType.unconditional,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | RalfSequenceInput
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[Tensor, "..."]
        | Mapping[str, Shaped[Tensor, "..."]],
    ]
    | None = None,
    retrieval_table: RalfRetrievalTable | None = None,
    query_ids: Sequence[int | str] | None = None,
    relations: RalfRelationshipTable | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    temperature: float = 1.0,
    top_k: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
)

Generate layouts through the RALF public interface.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster/content images. When omitted, the pipeline uses a zero image for smoke/debug calls; converted checkpoints were trained with real content inputs.

None
saliency ImageInput | Sequence[ImageInput] | None

Optional saliency maps.

None
batch_size int

Batch size when images are absent.

1
seed int | None

Convenience seed used only when generator is absent.

None
generator Generator | None

PyTorch generator; takes precedence over seed.

None
condition_type ConditionType | str

Canonical condition type or alias.

unconditional
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | RalfSequenceInput | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[bool] | Sequence[Sequence[bool]] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element counts.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size for pixel boxes.

None
retrieved_layouts Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...']] | None

Explicit retrieved layouts. When no retrieval data is supplied, the model receives zero retrieval memory for smoke/debug calls rather than paper-equivalent retrieved examples.

None
retrieved_images RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved images.

None
retrieved_saliency RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved saliency maps.

None
retrieved_indexes Int[Tensor, 'batch candidates'] | Sequence[Sequence[int]] | None

Explicit retrieved indexes.

None
retrieval Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...'] | Mapping[str, Shaped[Tensor, '...']]] | None

Canonical v2 retrieval container.

None
retrieval_table RalfRetrievalTable | None

Optional model-side retrieval table.

None
query_ids Sequence[int | str] | None

Query ids used for table lookup when explicit examples are absent.

None
relations RalfRelationshipTable | None

Optional relation constraints.

None
num_inference_steps int | None

Reserved v1 argument.

None
output_type Literal['dataclass', 'dict']

dataclass or dict.

'dataclass'
return_intermediates bool

Whether to return retrieval debug metadata.

False
temperature float

Sampling temperature.

1.0
top_k int | None

Optional top-k sampling limit.

None

Returns:

Type Description
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...'] | dict[int, str] | Mapping[str, Shaped[Tensor, '...']] | None]

LayoutGenerationOutput or dictionary.

Source code in models/ralf/src/ralf/pipeline_ralf.py
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
@torch.no_grad()
def __call__(  # ty: ignore[invalid-method-override]
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput | Sequence[ImageInput] | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: torch.Generator | None = None,
    condition_type: ConditionType | str = ConditionType.unconditional,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[torch.Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[torch.Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[torch.Tensor, "..."]
        | Mapping[str, Shaped[torch.Tensor, "..."]],
    ]
    | None = None,
    retrieval_table: RalfRetrievalTable | None = None,
    query_ids: Sequence[int | str] | None = None,
    relations: RalfRelationshipTable | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    temperature: float = 1.0,
    top_k: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
):
    """Generate layouts through the RALF public interface.

    Args:
        images: Poster/content images. When omitted, the pipeline uses a
            zero image for smoke/debug calls; converted checkpoints were
            trained with real content inputs.
        saliency: Optional saliency maps.
        batch_size: Batch size when images are absent.
        seed: Convenience seed used only when `generator` is absent.
        generator: PyTorch generator; takes precedence over `seed`.
        condition_type: Canonical condition type or alias.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Optional requested element counts.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size for pixel boxes.
        retrieved_layouts: Explicit retrieved layouts. When no retrieval data is
            supplied, the model receives zero retrieval memory for smoke/debug
            calls rather than paper-equivalent retrieved examples.
        retrieved_images: Explicit retrieved images.
        retrieved_saliency: Explicit retrieved saliency maps.
        retrieved_indexes: Explicit retrieved indexes.
        retrieval: Canonical v2 retrieval container.
        retrieval_table: Optional model-side retrieval table.
        query_ids: Query ids used for table lookup when explicit examples are absent.
        relations: Optional relation constraints.
        num_inference_steps: Reserved v1 argument.
        output_type: `dataclass` or `dict`.
        return_intermediates: Whether to return retrieval debug metadata.
        temperature: Sampling temperature.
        top_k: Optional top-k sampling limit.

    Returns:
        LayoutGenerationOutput or dictionary.
    """
    _ = (num_elements, num_inference_steps)
    condition = normalize_condition_type(condition_type)
    if condition not in SUPPORTED_GENERATION_CONDITIONS:
        raise NotImplementedError(
            "This RALF port currently supports unconditional, label, "
            "label_size, completion, refinement, relation, retrieval, and "
            "content_image; "
            f"got {condition}"
        )

    encoded = self.processor(
        images=images,
        saliency=saliency,
        condition_type=condition,
        labels=labels,
        bbox=bbox,
        mask=mask,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas_size,
        retrieved_layouts=retrieved_layouts,
        retrieved_images=retrieved_images,
        retrieved_saliency=retrieved_saliency,
        retrieved_indexes=retrieved_indexes,
        retrieval=retrieval,
        batch_size=batch_size,
    )
    model_device = next(self.model.parameters()).device
    generation_generator = self.prepare_generator(
        generator=generator,
        seed=seed,
        device=model_device,
    )
    intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]] = {}
    if "retrieval" in encoded:
        retrieval_batch = encoded["retrieval"]
        if retrieval_batch.indexes is not None:
            intermediates["retrieval"] = {"indexes": retrieval_batch.indexes}
    elif retrieval_table is not None and query_ids is not None:
        intermediates["retrieval"] = {"indexes": retrieval_table.lookup(query_ids)}
    sequences = self.model._generate_sequences(
        encoded["input_ids"].to(model_device),
        pixel_values=encoded["pixel_values"].to(model_device),
        saliency=encoded["saliency"].to(model_device),
        attention_mask=encoded["attention_mask"].to(model_device),
        max_length=self.config.max_token_length,
        temperature=temperature,
        top_k=top_k,
        generator=generation_generator,
        token_mask=self.processor.layout_tokenizer.token_mask(model_device),
        retrieved=encoded.get("retrieval"),
        condition_type=cast(RalfConfigTaskName, str(condition)),
        constraint_input_ids=encoded["input_ids"].to(model_device),
        constraint_mask=encoded["attention_mask"].to(model_device),
        constraint_element_mask=encoded["constraint_mask"].to(model_device),
        relationship_table=relations,
        sample_ids=query_ids,
    )
    return self.processor.post_process_layouts(
        sequences.cpu(),
        output_type=output_type,
        intermediates=intermediates if return_intermediates else None,
    )

processing_ralf

Processor for RALF images, conditions, retrieval, and output decoding.

RalfProcessor

Bases: ProcessorMixin

Assemble RALF model inputs and decode generated layouts.

Parameters:

Name Type Description Default
image_processor RalfImageProcessor

Image/saliency processor.

required
layout_tokenizer RalfLayoutTokenizer

Numeric layout tokenizer.

required

Examples:

>>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=2))
>>> encoded = processor(batch_size=1, condition_type="unconditional")
>>> "input_ids" in encoded
True
Source code in models/ralf/src/ralf/processing_ralf.py
 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
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
455
456
457
class RalfProcessor(ProcessorMixin):
    """Assemble RALF model inputs and decode generated layouts.

    Args:
        image_processor: Image/saliency processor.
        layout_tokenizer: Numeric layout tokenizer.

    Examples:
        >>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=2))
        >>> encoded = processor(batch_size=1, condition_type="unconditional")
        >>> "input_ids" in encoded
        True
    """

    attributes = ["image_processor", "layout_tokenizer"]
    image_processor_class = "RalfImageProcessor"
    tokenizer_class = "RalfLayoutTokenizer"

    def __init__(
        self,
        image_processor: RalfImageProcessor,
        layout_tokenizer: RalfLayoutTokenizer,
    ) -> None:
        """Initialize processor components."""
        self.image_processor = image_processor
        self.layout_tokenizer = layout_tokenizer
        super().__init__(image_processor, layout_tokenizer)

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        push_to_hub: bool = False,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Save local RALF processor components.

        Args:
            save_directory: Directory to write processor files.
            push_to_hub: Accepted for `ProcessorMixin` compatibility; ignored.
            kwargs: Accepted for `ProcessorMixin` compatibility; ignored.

        Examples:
            >>> import tempfile
            >>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=1))
            >>> with tempfile.TemporaryDirectory() as path:
            ...     processor.save_pretrained(path)
            ...     bool((Path(path) / "processor_config.json").exists())
            True
        """
        _ = (push_to_hub, kwargs)
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        self.image_processor.save_pretrained(root)
        self.layout_tokenizer.save_pretrained(root)
        (root / "processor_config.json").write_text(
            json.dumps(
                {
                    "processor_class": self.__class__.__name__,
                    "image_processor_class": self.image_processor.__class__.__name__,
                    "layout_tokenizer_class": self.layout_tokenizer.__class__.__name__,
                },
                indent=2,
                sort_keys=True,
            )
        )

    @classmethod
    def from_pretrained(
        cls,
        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",
        *,
        subfolder: str | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> "RalfProcessor":
        """Load local RALF processor components without Auto registration."""
        _ = (cache_dir, force_download, token, revision, kwargs)
        root = Path(pretrained_model_name_or_path)
        if subfolder is not None:
            root = root / subfolder
        config = RalfConfig.from_pretrained(root, local_files_only=local_files_only)
        return cls(
            image_processor=RalfImageProcessor.from_pretrained(root),
            layout_tokenizer=RalfLayoutTokenizer.from_pretrained(
                root,
                config=config,
                local_files_only=local_files_only,
            ),
        )

    @classmethod
    def _load_image_processor_from_pretrained(
        cls,
        sub_processor_type: str,
        pretrained_model_name_or_path: str | PathLike[str],
        subfolder: str = "",
        **kwargs: str | int | float | bool | None,
    ) -> RalfImageProcessor:
        """Load the local image processor for `ProcessorMixin.from_pretrained`."""
        _ = (sub_processor_type, kwargs)
        path = Path(pretrained_model_name_or_path)
        root = path / subfolder if subfolder else path
        return RalfImageProcessor.from_pretrained(root)

    @classmethod
    def _load_layout_tokenizer_from_pretrained(
        cls,
        sub_processor_type: str,
        pretrained_model_name_or_path: str | PathLike[str],
        subfolder: str = "",
        **kwargs: str | int | float | bool | None,
    ) -> RalfLayoutTokenizer:
        """Load the local layout tokenizer for `ProcessorMixin.from_pretrained`."""
        _ = sub_processor_type
        path = Path(pretrained_model_name_or_path)
        root = path / subfolder if subfolder else path
        return RalfLayoutTokenizer.from_pretrained(
            root,
            local_files_only=bool(kwargs.get("local_files_only", False)),
        )

    @classmethod
    def from_config(cls, config: RalfConfig) -> "RalfProcessor":
        """Create processor components from a config."""
        return cls(
            image_processor=RalfImageProcessor(
                cast(tuple[int, int] | None, config.image_size)
            ),
            layout_tokenizer=RalfLayoutTokenizer(config),
        )

    @property
    def config(self) -> RalfConfig:
        """Return tokenizer-backed RALF config."""
        return self.layout_tokenizer.config

    def normalize_condition_type(
        self, condition_type: ConditionType | str
    ) -> ConditionType:
        """Normalize a public condition string."""
        return normalize_condition_type(condition_type)

    def _coerce_labels(
        self,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None,
        batch_size: int,
    ) -> Int[torch.Tensor, "batch elements"]:
        if labels is None:
            return torch.zeros((batch_size, 0), dtype=torch.long)
        if isinstance(labels, torch.Tensor):
            tensor = labels.long()
            return tensor.unsqueeze(0) if tensor.ndim == 1 else tensor
        labels_list = list(labels)
        if not labels_list:
            return torch.zeros((batch_size, 0), dtype=torch.long)
        first = labels_list[0]
        rows = (
            labels_list
            if isinstance(first, Sequence) and not isinstance(first, str)
            else [labels_list]
        )
        label2id = cast(dict[str, int], self.config.label2id)
        out = []
        typed_rows = cast(list[Sequence[int | str]], rows)
        for row in typed_rows:
            values = []
            for item in row:
                if isinstance(item, str):
                    values.append(label2id[item.lower()])
                else:
                    values.append(int(item))
            out.append(values)
        return torch.tensor(out, dtype=torch.long)

    def _coerce_bbox(
        self,
        bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None,
        *,
        labels: Int[torch.Tensor, "batch elements"],
        box_format: BoxFormat | str,
        normalized: bool,
        canvas_size: tuple[int, int] | None,
    ) -> Float[torch.Tensor, "batch elements 4"]:
        if bbox is None:
            return torch.zeros((labels.size(0), labels.size(1), 4), dtype=torch.float32)
        tensor = torch.as_tensor(bbox, dtype=torch.float32)
        if tensor.ndim == 2:
            tensor = tensor.unsqueeze(0)
        if not normalized:
            if canvas_size is None:
                raise ValueError("canvas_size is required when normalized=False")

            return normalize_boxes(
                tensor, canvas_size=canvas_size, box_format=box_format
            )
        fmt = normalize_box_format(box_format)
        if fmt is BoxFormat.xywh:
            return tensor.clamp(0.0, 1.0)
        if fmt is BoxFormat.ltwh:
            from laygen.common.bbox import ltwh_to_xywh

            return ltwh_to_xywh(tensor).clamp(0.0, 1.0)
        from laygen.common.bbox import ltrb_to_xywh

        return ltrb_to_xywh(tensor).clamp(0.0, 1.0)

    def __call__(
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        saliency: ImageInput | Sequence[ImageInput] | None = None,
        condition_type: ConditionType | str = ConditionType.unconditional,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[bool]
        | Sequence[Sequence[bool]]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        retrieved_layouts: Mapping[
            str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
        ]
        | None = None,
        retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
        retrieved_saliency: RalfSequenceInput
        | Shaped[torch.Tensor, "..."]
        | None = None,
        retrieved_indexes: Int[torch.Tensor, "batch candidates"]
        | Sequence[Sequence[int]]
        | None = None,
        retrieval: Mapping[
            str,
            RalfRetrievalValue
            | Shaped[torch.Tensor, "..."]
            | Mapping[str, Shaped[torch.Tensor, "..."]],
        ]
        | None = None,
        relations: Mapping[str, RalfRetrievalValue] | None = None,
        batch_size: int = 1,
        return_tensors: RalfReturnTensor = "pt",
    ) -> BatchEncoding:
        """Encode public RALF inputs into tensors.

        Args:
            images: Poster/content image inputs.
            saliency: Optional saliency maps.
            condition_type: Canonical condition type or alias.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Optional requested element counts.
            box_format: Input box format.
            normalized: Whether `bbox` is already normalized.
            canvas_size: Pixel canvas size for unnormalized boxes.
            retrieved_layouts: Explicit retrieved layouts.
            retrieved_images: Explicit retrieved images.
            retrieved_saliency: Explicit retrieved saliency maps.
            retrieved_indexes: Explicit retrieved cache indexes.
            retrieval: Canonical v2 retrieval container.
            relations: Optional relation constraints.
            batch_size: Batch size used when no labels/images are supplied.
            return_tensors: Tensor format; only `pt` is supported.

        Returns:
            BatchEncoding containing model inputs.
        """
        _ = (num_elements, relations)
        condition = normalize_condition_type(condition_type)
        image_batch = self.image_processor.preprocess(
            images, saliency, return_tensors=return_tensors
        )
        batch_size = (
            int(image_batch["pixel_values"].size(0))
            if images is not None
            else batch_size
        )
        label_tensor = self._coerce_labels(labels, batch_size)
        bbox_tensor = self._coerce_bbox(
            bbox,
            labels=label_tensor,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        if mask is None:
            mask_tensor = torch.ones(label_tensor.shape, dtype=torch.bool)
        else:
            mask_tensor = torch.as_tensor(mask, dtype=torch.bool)
            if mask_tensor.ndim == 1:
                mask_tensor = mask_tensor.unsqueeze(0)
        tokenized = self.layout_tokenizer.encode_layout(
            labels=label_tensor,
            bbox=bbox_tensor,
            mask=mask_tensor,
        )
        output = BatchEncoding(
            {
                **image_batch,
                **tokenized,
                "condition_type": condition,
                "constraint_labels": label_tensor,
                "constraint_bbox": bbox_tensor,
                "constraint_mask": mask_tensor,
            }
        )
        retrieval_payload = retrieval or {}
        explicit_layouts = (
            retrieved_layouts
            or retrieval_payload.get("items")
            or retrieval_payload.get("examples")
        )
        if explicit_layouts is not None:
            output["retrieval"] = self._build_retrieval_batch(
                cast(
                    Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]]
                    | RalfSequenceInput
                    | Shaped[torch.Tensor, "..."],
                    explicit_layouts,
                ),
                cast(
                    Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                    retrieved_images
                    if retrieved_images is not None
                    else retrieval_payload.get("images"),
                ),
                cast(
                    Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                    retrieved_saliency
                    if retrieved_saliency is not None
                    else retrieval_payload.get("saliency"),
                ),
                cast(
                    Int[torch.Tensor, "batch candidates"]
                    | Sequence[Sequence[int]]
                    | None,
                    retrieved_indexes
                    if retrieved_indexes is not None
                    else retrieval_payload.get("ids"),
                ),
            )
        return output

    def _build_retrieval_batch(
        self,
        layouts: Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]]
        | RalfSequenceInput
        | Shaped[torch.Tensor, "..."],
        images: Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
        saliency: Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
        indexes: Int[torch.Tensor, "batch candidates"] | Sequence[Sequence[int]] | None,
    ) -> RalfRetrievedBatch:
        data = cast(
            Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]],
            layouts if isinstance(layouts, Mapping) else {"bbox": layouts},
        )
        bbox = torch.as_tensor(data["bbox"], dtype=torch.float32)
        labels = torch.as_tensor(
            data.get("labels", torch.zeros(bbox.shape[:-1])), dtype=torch.long
        )
        mask = torch.as_tensor(
            data.get("mask", torch.ones(labels.shape)), dtype=torch.bool
        )
        batch, candidates = bbox.shape[:2]
        image_tensor = torch.zeros(batch, candidates, 3, 1, 1)
        saliency_tensor = torch.zeros(batch, candidates, 1, 1, 1)
        if images is not None:
            image_tensor = torch.as_tensor(images, dtype=torch.float32)
        if saliency is not None:
            saliency_tensor = torch.as_tensor(saliency, dtype=torch.float32)
        index_tensor = (
            None if indexes is None else torch.as_tensor(indexes, dtype=torch.long)
        )
        return RalfRetrievedBatch(
            image=image_tensor,
            saliency=saliency_tensor,
            bbox=bbox,
            labels=labels,
            mask=mask,
            indexes=index_tensor,
        )

    def post_process_layouts(
        self,
        sequences: Int[torch.Tensor, "batch tokens"],
        *,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]]
        | None = None,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Shaped[torch.Tensor, "..."]
            | dict[int, str]
            | Mapping[str, Shaped[torch.Tensor, "..."]]
            | None,
        ]
    ):
        """Decode generated token ids to the common output schema."""
        decoded = self.layout_tokenizer.decode_layout(sequences.cpu())
        output = LayoutGenerationOutput(
            bbox=decoded["bbox"],
            labels=decoded["labels"],
            mask=decoded["mask"],
            id2label=cast(dict[int, str], self.config.id2label),
            sequences=sequences.cpu(),
            intermediates=intermediates,
        )
        if output_type == "dict":
            return dict(output.items())
        return output

config property

config: RalfConfig

Return tokenizer-backed RALF config.

__init__

__init__(
    image_processor: RalfImageProcessor,
    layout_tokenizer: RalfLayoutTokenizer,
) -> None

Initialize processor components.

Source code in models/ralf/src/ralf/processing_ralf.py
52
53
54
55
56
57
58
59
60
def __init__(
    self,
    image_processor: RalfImageProcessor,
    layout_tokenizer: RalfLayoutTokenizer,
) -> None:
    """Initialize processor components."""
    self.image_processor = image_processor
    self.layout_tokenizer = layout_tokenizer
    super().__init__(image_processor, layout_tokenizer)

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None

Save local RALF processor components.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Directory to write processor files.

required
push_to_hub bool

Accepted for ProcessorMixin compatibility; ignored.

False
kwargs str | int | float | bool | None

Accepted for ProcessorMixin compatibility; ignored.

{}

Examples:

>>> import tempfile
>>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=1))
>>> with tempfile.TemporaryDirectory() as path:
...     processor.save_pretrained(path)
...     bool((Path(path) / "processor_config.json").exists())
True
Source code in models/ralf/src/ralf/processing_ralf.py
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
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Save local RALF processor components.

    Args:
        save_directory: Directory to write processor files.
        push_to_hub: Accepted for `ProcessorMixin` compatibility; ignored.
        kwargs: Accepted for `ProcessorMixin` compatibility; ignored.

    Examples:
        >>> import tempfile
        >>> processor = RalfProcessor.from_config(RalfConfig(max_seq_length=1))
        >>> with tempfile.TemporaryDirectory() as path:
        ...     processor.save_pretrained(path)
        ...     bool((Path(path) / "processor_config.json").exists())
        True
    """
    _ = (push_to_hub, kwargs)
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    self.image_processor.save_pretrained(root)
    self.layout_tokenizer.save_pretrained(root)
    (root / "processor_config.json").write_text(
        json.dumps(
            {
                "processor_class": self.__class__.__name__,
                "image_processor_class": self.image_processor.__class__.__name__,
                "layout_tokenizer_class": self.layout_tokenizer.__class__.__name__,
            },
            indent=2,
            sort_keys=True,
        )
    )

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",
    *,
    subfolder: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> "RalfProcessor"

Load local RALF processor components without Auto registration.

Source code in models/ralf/src/ralf/processing_ralf.py
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
@classmethod
def from_pretrained(
    cls,
    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",
    *,
    subfolder: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> "RalfProcessor":
    """Load local RALF processor components without Auto registration."""
    _ = (cache_dir, force_download, token, revision, kwargs)
    root = Path(pretrained_model_name_or_path)
    if subfolder is not None:
        root = root / subfolder
    config = RalfConfig.from_pretrained(root, local_files_only=local_files_only)
    return cls(
        image_processor=RalfImageProcessor.from_pretrained(root),
        layout_tokenizer=RalfLayoutTokenizer.from_pretrained(
            root,
            config=config,
            local_files_only=local_files_only,
        ),
    )

from_config classmethod

from_config(config: RalfConfig) -> 'RalfProcessor'

Create processor components from a config.

Source code in models/ralf/src/ralf/processing_ralf.py
159
160
161
162
163
164
165
166
167
@classmethod
def from_config(cls, config: RalfConfig) -> "RalfProcessor":
    """Create processor components from a config."""
    return cls(
        image_processor=RalfImageProcessor(
            cast(tuple[int, int] | None, config.image_size)
        ),
        layout_tokenizer=RalfLayoutTokenizer(config),
    )

normalize_condition_type

normalize_condition_type(
    condition_type: ConditionType | str,
) -> ConditionType

Normalize a public condition string.

Source code in models/ralf/src/ralf/processing_ralf.py
174
175
176
177
178
def normalize_condition_type(
    self, condition_type: ConditionType | str
) -> ConditionType:
    """Normalize a public condition string."""
    return normalize_condition_type(condition_type)

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput
    | Sequence[ImageInput]
    | None = None,
    condition_type: ConditionType
    | str = ConditionType.unconditional,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | RalfSequenceInput
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[Tensor, "..."]
        | Mapping[str, Shaped[Tensor, "..."]],
    ]
    | None = None,
    relations: Mapping[str, RalfRetrievalValue]
    | None = None,
    batch_size: int = 1,
    return_tensors: RalfReturnTensor = "pt",
) -> BatchEncoding

Encode public RALF inputs into tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster/content image inputs.

None
saliency ImageInput | Sequence[ImageInput] | None

Optional saliency maps.

None
condition_type ConditionType | str

Canonical condition type or alias.

unconditional
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | RalfSequenceInput | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[bool] | Sequence[Sequence[bool]] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element counts.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether bbox is already normalized.

True
canvas_size tuple[int, int] | None

Pixel canvas size for unnormalized boxes.

None
retrieved_layouts Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...']] | None

Explicit retrieved layouts.

None
retrieved_images RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved images.

None
retrieved_saliency RalfSequenceInput | Shaped[Tensor, '...'] | None

Explicit retrieved saliency maps.

None
retrieved_indexes Int[Tensor, 'batch candidates'] | Sequence[Sequence[int]] | None

Explicit retrieved cache indexes.

None
retrieval Mapping[str, RalfRetrievalValue | Shaped[Tensor, '...'] | Mapping[str, Shaped[Tensor, '...']]] | None

Canonical v2 retrieval container.

None
relations Mapping[str, RalfRetrievalValue] | None

Optional relation constraints.

None
batch_size int

Batch size used when no labels/images are supplied.

1
return_tensors RalfReturnTensor

Tensor format; only pt is supported.

'pt'

Returns:

Type Description
BatchEncoding

BatchEncoding containing model inputs.

Source code in models/ralf/src/ralf/processing_ralf.py
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
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
def __call__(
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    saliency: ImageInput | Sequence[ImageInput] | None = None,
    condition_type: ConditionType | str = ConditionType.unconditional,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."] | RalfSequenceInput | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[bool]
    | Sequence[Sequence[bool]]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    retrieved_layouts: Mapping[
        str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]
    ]
    | None = None,
    retrieved_images: RalfSequenceInput | Shaped[torch.Tensor, "..."] | None = None,
    retrieved_saliency: RalfSequenceInput
    | Shaped[torch.Tensor, "..."]
    | None = None,
    retrieved_indexes: Int[torch.Tensor, "batch candidates"]
    | Sequence[Sequence[int]]
    | None = None,
    retrieval: Mapping[
        str,
        RalfRetrievalValue
        | Shaped[torch.Tensor, "..."]
        | Mapping[str, Shaped[torch.Tensor, "..."]],
    ]
    | None = None,
    relations: Mapping[str, RalfRetrievalValue] | None = None,
    batch_size: int = 1,
    return_tensors: RalfReturnTensor = "pt",
) -> BatchEncoding:
    """Encode public RALF inputs into tensors.

    Args:
        images: Poster/content image inputs.
        saliency: Optional saliency maps.
        condition_type: Canonical condition type or alias.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Optional requested element counts.
        box_format: Input box format.
        normalized: Whether `bbox` is already normalized.
        canvas_size: Pixel canvas size for unnormalized boxes.
        retrieved_layouts: Explicit retrieved layouts.
        retrieved_images: Explicit retrieved images.
        retrieved_saliency: Explicit retrieved saliency maps.
        retrieved_indexes: Explicit retrieved cache indexes.
        retrieval: Canonical v2 retrieval container.
        relations: Optional relation constraints.
        batch_size: Batch size used when no labels/images are supplied.
        return_tensors: Tensor format; only `pt` is supported.

    Returns:
        BatchEncoding containing model inputs.
    """
    _ = (num_elements, relations)
    condition = normalize_condition_type(condition_type)
    image_batch = self.image_processor.preprocess(
        images, saliency, return_tensors=return_tensors
    )
    batch_size = (
        int(image_batch["pixel_values"].size(0))
        if images is not None
        else batch_size
    )
    label_tensor = self._coerce_labels(labels, batch_size)
    bbox_tensor = self._coerce_bbox(
        bbox,
        labels=label_tensor,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas_size,
    )
    if mask is None:
        mask_tensor = torch.ones(label_tensor.shape, dtype=torch.bool)
    else:
        mask_tensor = torch.as_tensor(mask, dtype=torch.bool)
        if mask_tensor.ndim == 1:
            mask_tensor = mask_tensor.unsqueeze(0)
    tokenized = self.layout_tokenizer.encode_layout(
        labels=label_tensor,
        bbox=bbox_tensor,
        mask=mask_tensor,
    )
    output = BatchEncoding(
        {
            **image_batch,
            **tokenized,
            "condition_type": condition,
            "constraint_labels": label_tensor,
            "constraint_bbox": bbox_tensor,
            "constraint_mask": mask_tensor,
        }
    )
    retrieval_payload = retrieval or {}
    explicit_layouts = (
        retrieved_layouts
        or retrieval_payload.get("items")
        or retrieval_payload.get("examples")
    )
    if explicit_layouts is not None:
        output["retrieval"] = self._build_retrieval_batch(
            cast(
                Mapping[str, RalfRetrievalValue | Shaped[torch.Tensor, "..."]]
                | RalfSequenceInput
                | Shaped[torch.Tensor, "..."],
                explicit_layouts,
            ),
            cast(
                Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                retrieved_images
                if retrieved_images is not None
                else retrieval_payload.get("images"),
            ),
            cast(
                Shaped[torch.Tensor, "..."] | RalfSequenceInput | None,
                retrieved_saliency
                if retrieved_saliency is not None
                else retrieval_payload.get("saliency"),
            ),
            cast(
                Int[torch.Tensor, "batch candidates"]
                | Sequence[Sequence[int]]
                | None,
                retrieved_indexes
                if retrieved_indexes is not None
                else retrieval_payload.get("ids"),
            ),
        )
    return output

post_process_layouts

post_process_layouts(
    sequences: Int[Tensor, "batch tokens"],
    *,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    intermediates: dict[
        str, Mapping[str, Shaped[Tensor, "..."] | str]
    ]
    | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
)

Decode generated token ids to the common output schema.

Source code in models/ralf/src/ralf/processing_ralf.py
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
455
456
457
def post_process_layouts(
    self,
    sequences: Int[torch.Tensor, "batch tokens"],
    *,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    intermediates: dict[str, Mapping[str, Shaped[torch.Tensor, "..."] | str]]
    | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Shaped[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, Shaped[torch.Tensor, "..."]]
        | None,
    ]
):
    """Decode generated token ids to the common output schema."""
    decoded = self.layout_tokenizer.decode_layout(sequences.cpu())
    output = LayoutGenerationOutput(
        bbox=decoded["bbox"],
        labels=decoded["labels"],
        mask=decoded["mask"],
        id2label=cast(dict[int, str], self.config.id2label),
        sequences=sequences.cpu(),
        intermediates=intermediates,
    )
    if output_type == "dict":
        return dict(output.items())
    return output

retrieval

Retrieval containers and adapters for RALF.

RalfRetrievedBatch dataclass

Batch of explicit retrieved examples for RALF.

Parameters:

Name Type Description Default
image Float[Tensor, 'batch candidates channels height width']

Retrieved RGB images with shape (batch, candidates, channels, height, width).

required
saliency Float[Tensor, 'batch candidates 1 height width']

Retrieved saliency maps with shape (batch, candidates, 1, height, width).

required
bbox Float[Tensor, 'batch candidates elements 4']

Retrieved normalized center xywh boxes.

required
labels Int[Tensor, 'batch candidates elements']

Retrieved dataset-local labels.

required
mask Bool[Tensor, 'batch candidates elements']

Retrieved valid-element masks.

required
indexes Int[Tensor, 'batch candidates'] | None

Optional selected cache indexes.

None
Source code in models/ralf/src/ralf/retrieval.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass
class RalfRetrievedBatch:
    """Batch of explicit retrieved examples for RALF.

    Args:
        image: Retrieved RGB images with shape `(batch, candidates, channels, height, width)`.
        saliency: Retrieved saliency maps with shape `(batch, candidates, 1, height, width)`.
        bbox: Retrieved normalized center `xywh` boxes.
        labels: Retrieved dataset-local labels.
        mask: Retrieved valid-element masks.
        indexes: Optional selected cache indexes.
    """

    image: Float[torch.Tensor, "batch candidates channels height width"]
    saliency: Float[torch.Tensor, "batch candidates 1 height width"]
    bbox: Float[torch.Tensor, "batch candidates elements 4"]
    labels: Int[torch.Tensor, "batch candidates elements"]
    mask: Bool[torch.Tensor, "batch candidates elements"]
    indexes: Int[torch.Tensor, "batch candidates"] | None = None

RalfRetrievalTable

Lookup table from query ids to retrieved training indexes.

Parameters:

Name Type Description Default
table Mapping[int | str, Sequence[int]]

Mapping from query ids to ordered retrieved ids.

required
top_k int

Number of retrieved ids returned per query.

required

Examples:

>>> table = RalfRetrievalTable({"a": [3, 4, 5]}, top_k=2)
>>> table.lookup(["a"]).tolist()
[[3, 4]]
Source code in models/ralf/src/ralf/retrieval.py
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
class RalfRetrievalTable:
    """Lookup table from query ids to retrieved training indexes.

    Args:
        table: Mapping from query ids to ordered retrieved ids.
        top_k: Number of retrieved ids returned per query.

    Examples:
        >>> table = RalfRetrievalTable({"a": [3, 4, 5]}, top_k=2)
        >>> table.lookup(["a"]).tolist()
        [[3, 4]]
    """

    def __init__(self, table: Mapping[int | str, Sequence[int]], top_k: int) -> None:
        """Initialize lookup table."""
        self.table = {
            str(key): [int(value) for value in values] for key, values in table.items()
        }
        self.top_k = int(top_k)

    @classmethod
    def from_pretrained(
        cls, path: str | Path, top_k: int | None = None
    ) -> "RalfRetrievalTable":
        """Load `retrieval_table.json` from a checkpoint directory."""
        root = Path(path)
        with (root / "retrieval_table.json").open() as f:
            payload = json.load(f)
        return cls(payload["table"], top_k=top_k or int(payload["top_k"]))

    def save_pretrained(self, save_directory: str | Path) -> tuple[str]:
        """Save the table next to converted checkpoint metadata."""
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        path = root / "retrieval_table.json"
        with path.open("w") as f:
            json.dump(
                {"top_k": self.top_k, "table": self.table}, f, indent=2, sort_keys=True
            )
        return (str(path),)

    def lookup(self, ids: Sequence[int | str]) -> Int[torch.Tensor, "batch candidates"]:
        """Return retrieved indexes for query ids."""
        rows = []
        for item in ids:
            values = self.table[str(item)][: self.top_k]
            if len(values) < self.top_k:
                values = values + [-1] * (self.top_k - len(values))
            rows.append(values)
        return torch.tensor(rows, dtype=torch.long)

__init__

__init__(
    table: Mapping[int | str, Sequence[int]], top_k: int
) -> None

Initialize lookup table.

Source code in models/ralf/src/ralf/retrieval.py
48
49
50
51
52
53
def __init__(self, table: Mapping[int | str, Sequence[int]], top_k: int) -> None:
    """Initialize lookup table."""
    self.table = {
        str(key): [int(value) for value in values] for key, values in table.items()
    }
    self.top_k = int(top_k)

from_pretrained classmethod

from_pretrained(
    path: str | Path, top_k: int | None = None
) -> "RalfRetrievalTable"

Load retrieval_table.json from a checkpoint directory.

Source code in models/ralf/src/ralf/retrieval.py
55
56
57
58
59
60
61
62
63
@classmethod
def from_pretrained(
    cls, path: str | Path, top_k: int | None = None
) -> "RalfRetrievalTable":
    """Load `retrieval_table.json` from a checkpoint directory."""
    root = Path(path)
    with (root / "retrieval_table.json").open() as f:
        payload = json.load(f)
    return cls(payload["table"], top_k=top_k or int(payload["top_k"]))

save_pretrained

save_pretrained(save_directory: str | Path) -> tuple[str]

Save the table next to converted checkpoint metadata.

Source code in models/ralf/src/ralf/retrieval.py
65
66
67
68
69
70
71
72
73
74
def save_pretrained(self, save_directory: str | Path) -> tuple[str]:
    """Save the table next to converted checkpoint metadata."""
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    path = root / "retrieval_table.json"
    with path.open("w") as f:
        json.dump(
            {"top_k": self.top_k, "table": self.table}, f, indent=2, sort_keys=True
        )
    return (str(path),)

lookup

lookup(
    ids: Sequence[int | str],
) -> Int[torch.Tensor, "batch candidates"]

Return retrieved indexes for query ids.

Source code in models/ralf/src/ralf/retrieval.py
76
77
78
79
80
81
82
83
84
def lookup(self, ids: Sequence[int | str]) -> Int[torch.Tensor, "batch candidates"]:
    """Return retrieved indexes for query ids."""
    rows = []
    for item in ids:
        values = self.table[str(item)][: self.top_k]
        if len(values) < self.top_k:
            values = values + [-1] * (self.top_k - len(values))
        rows.append(values)
    return torch.tensor(rows, dtype=torch.long)

retrieved_batch_to_model_inputs

retrieved_batch_to_model_inputs(
    batch: RalfRetrievedBatch,
) -> dict[str, Shaped[torch.Tensor, "..."]]

Convert explicit retrieved examples to model input field names.

Source code in models/ralf/src/ralf/retrieval.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def retrieved_batch_to_model_inputs(
    batch: RalfRetrievedBatch,
) -> dict[str, Shaped[torch.Tensor, "..."]]:
    """Convert explicit retrieved examples to model input field names."""
    x, y, w, h = batch.bbox.unbind(dim=-1)
    output = {
        "image": batch.image,
        "saliency": batch.saliency,
        "center_x": x,
        "center_y": y,
        "width": w,
        "height": h,
        "label": batch.labels,
        "mask": batch.mask,
    }
    if batch.indexes is not None:
        output["index"] = batch.indexes
    return output

model_inputs_to_retrieved_batch

model_inputs_to_retrieved_batch(
    data: Mapping[str, Shaped[Tensor, "..."]],
) -> RalfRetrievedBatch

Convert model input fields to RalfRetrievedBatch.

Source code in models/ralf/src/ralf/retrieval.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def model_inputs_to_retrieved_batch(
    data: Mapping[str, Shaped[torch.Tensor, "..."]],
) -> RalfRetrievedBatch:
    """Convert model input fields to `RalfRetrievedBatch`."""
    bbox = torch.stack(
        (
            data["center_x"],
            data["center_y"],
            data["width"],
            data["height"],
        ),
        dim=-1,
    )
    return RalfRetrievedBatch(
        image=data["image"],
        saliency=data["saliency"],
        bbox=bbox,
        labels=data["label"].long(),
        mask=data["mask"].bool(),
        indexes=data.get("index"),
    )

tokenization_ralf

Numeric layout tokenizer for RALF.

RalfLayoutTokenizer

Bases: PreTrainedTokenizer

PreTrainedTokenizer for RALF's numeric layout token sequences.

Parameters:

Name Type Description Default
config RalfConfig | None

RALF config that defines label and geometry vocabularies.

None
tokenizer_config_file str | None

Optional tokenizer metadata path loaded by from_pretrained.

None
kwargs str | int | float | bool | None

Standard PreTrainedTokenizer keyword arguments.

{}

Examples:

>>> tokenizer = RalfLayoutTokenizer(RalfConfig(max_seq_length=2))
>>> encoded = tokenizer.encode_layout(
...     labels=torch.tensor([[0]]),
...     bbox=torch.tensor([[[0.5, 0.5, 0.2, 0.2]]]),
...     mask=torch.tensor([[True]]),
... )
>>> encoded["input_ids"].shape[1] > 1
True
Source code in models/ralf/src/ralf/tokenization_ralf.py
 20
 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
 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
class RalfLayoutTokenizer(PreTrainedTokenizer):
    """PreTrainedTokenizer for RALF's numeric layout token sequences.

    Args:
        config: RALF config that defines label and geometry vocabularies.
        tokenizer_config_file: Optional tokenizer metadata path loaded by
            `from_pretrained`.
        kwargs: Standard `PreTrainedTokenizer` keyword arguments.

    Examples:
        >>> tokenizer = RalfLayoutTokenizer(RalfConfig(max_seq_length=2))
        >>> encoded = tokenizer.encode_layout(
        ...     labels=torch.tensor([[0]]),
        ...     bbox=torch.tensor([[[0.5, 0.5, 0.2, 0.2]]]),
        ...     mask=torch.tensor([[True]]),
        ... )
        >>> encoded["input_ids"].shape[1] > 1
        True
    """

    model_input_names = ["input_ids", "attention_mask"]
    vocab_files_names = {"tokenizer_config_file": TOKENIZER_CONFIG_FILE}

    def __init__(
        self,
        config: RalfConfig | None = None,
        tokenizer_config_file: str | None = None,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Initialize tokenizer metadata and synthetic token strings."""
        if config is None and tokenizer_config_file is not None:
            with Path(tokenizer_config_file).open() as f:
                config = RalfConfig(**json.load(f)["config"])
        if config is None:
            raise ValueError("RalfLayoutTokenizer requires an explicit config")

        self.config = config
        self._token2id = self._build_vocab()
        self._id2token = {idx: token for token, idx in self._token2id.items()}
        kwargs.setdefault("pad_token", "[pad]")
        kwargs.setdefault("bos_token", "[bos]")
        kwargs.setdefault("eos_token", "[eos]")
        kwargs.setdefault("unk_token", "[unk]")
        kwargs.setdefault("model_max_length", self.config.max_token_length + 1)
        kwargs.setdefault("clean_up_tokenization_spaces", False)
        super().__init__(
            **kwargs,
        )

    @property
    def vocab_size(self) -> int:
        """Return total vocabulary size."""
        return self.config.vocab_size

    def get_vocab(self) -> dict[str, int]:
        """Return synthetic token strings mapped to ids."""
        return dict(self._token2id)

    def _build_vocab(self) -> dict[str, int]:
        id2label = cast(dict[int, str], self.config.id2label)
        vocab = {f"label:{label}": int(idx) for idx, label in id2label.items()}
        for key in GEO_KEYS:
            start = self.config.bbox_token_offset(key)
            for idx in range(self.config.num_bin):
                vocab[f"{key}:{idx}"] = start + idx
        for token in self.config.special_tokens:
            vocab[f"[{token}]"] = self.config.special_token_id(token)
        return vocab

    def _tokenize(
        self, text: str, **kwargs: str | int | float | bool | None
    ) -> list[str]:
        _ = kwargs
        return text.strip().split()

    def _convert_token_to_id(self, token: str) -> int:
        return self._token2id.get(token, self.config.pad_token_id)

    def _convert_id_to_token(self, index: int) -> str:
        return self._id2token.get(int(index), "[unk]")

    def convert_tokens_to_string(self, tokens: list[str]) -> str:
        """Join synthetic layout tokens."""
        return " ".join(tokens)

    def save_vocabulary(
        self, save_directory: str, filename_prefix: str | None = None
    ) -> tuple[str, ...]:
        """Save tokenizer metadata for Hub-compatible loading."""
        out_dir = Path(save_directory)
        out_dir.mkdir(parents=True, exist_ok=True)
        name = (
            TOKENIZER_CONFIG_FILE
            if filename_prefix is None
            else f"{filename_prefix}-{TOKENIZER_CONFIG_FILE}"
        )
        path = out_dir / name
        with path.open("w") as f:
            json.dump({"config": self.config.to_dict()}, f, indent=2, sort_keys=True)
        return (str(path),)

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        legacy_format: bool | None = None,
        filename_prefix: str | None = None,
        push_to_hub: bool = False,
        **kwargs: str | int | float | bool | None,
    ) -> tuple[str, ...]:
        """Save tokenizer files and the paired `RalfConfig`.

        Args:
            save_directory: Output directory.
            legacy_format: Standard tokenizer save flag.
            filename_prefix: Optional filename prefix.
            push_to_hub: Whether to push through Hugging Face Hub helpers.
            kwargs: Reserved tokenizer save arguments.

        Returns:
            Written tokenizer file paths.
        """
        paths = super().save_pretrained(
            save_directory,
            legacy_format=legacy_format,
            filename_prefix=filename_prefix,
            push_to_hub=push_to_hub,
            **kwargs,
        )
        self.config.save_pretrained(save_directory)
        return paths

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str | PathLike[str],
        *inputs: str,
        config: RalfConfig | None = None,
        cache_dir: str | PathLike[str] | None = None,
        force_download: bool = False,
        local_files_only: bool = False,
        token: str | bool | None = None,
        revision: str = "main",
    ) -> "RalfLayoutTokenizer":
        """Load tokenizer metadata from a checkpoint directory."""
        if config is None:
            config = RalfConfig.from_pretrained(pretrained_model_name_or_path)
        loaded = super().from_pretrained(
            pretrained_model_name_or_path,
            *inputs,
            cache_dir=cache_dir,
            force_download=force_download,
            local_files_only=local_files_only,
            token=token,
            revision=revision,
            config=config,
        )
        return cast("RalfLayoutTokenizer", loaded)

    def _quantize(self, values: Float[torch.Tensor, "..."]) -> Int[torch.Tensor, "..."]:
        values = values.clamp(0.0, 1.0)
        boundaries = (
            torch.arange(
                1,
                self.config.num_bin + 1,
                device=values.device,
                dtype=values.dtype,
            )
            / self.config.num_bin
        )
        return torch.bucketize(values, boundaries).long()

    def _dequantize(self, ids: Int[torch.Tensor, "..."]) -> Float[torch.Tensor, "..."]:
        ids = ids.clamp(0, self.config.num_bin - 1)
        starts = ids.float() / self.config.num_bin
        return starts + (0.5 / self.config.num_bin)

    def encode_layout(
        self,
        *,
        labels: Int[torch.Tensor, "batch elements"],
        bbox: Float[torch.Tensor, "batch elements 4"],
        mask: Bool[torch.Tensor, "batch elements"] | None = None,
    ) -> BatchEncoding:
        """Encode public normalized center `xywh` layouts to RALF tokens.

        Args:
            labels: Dataset-local integer labels.
            bbox: Normalized center `xywh` boxes.
            mask: Valid-element mask. If omitted, every element is valid.

        Returns:
            BatchEncoding with `input_ids` and `attention_mask`.

        Raises:
            ValueError: If tensor ranks are invalid.
        """
        if labels.ndim != 2 or bbox.ndim != 3 or bbox.shape[-1] != 4:
            raise ValueError("labels must be (B,S) and bbox must be (B,S,4)")

        if mask is None:
            mask = torch.ones_like(labels, dtype=torch.bool)
        batch, elements = labels.shape
        max_elements = min(elements, self.config.max_seq_length)
        seq = labels.new_full(
            (batch, self.config.max_token_length),
            self.config.pad_token_id,
        )
        attention_mask = torch.zeros_like(seq, dtype=torch.bool)
        geometry = {
            "center_x": self._quantize(bbox[..., 0]),
            "center_y": self._quantize(bbox[..., 1]),
            "width": self._quantize(bbox[..., 2]),
            "height": self._quantize(bbox[..., 3]),
        }
        for element_idx in range(max_elements):
            for var_idx, key in enumerate(self.config.var_order):
                token_idx = element_idx * len(self.config.var_order) + var_idx
                valid = mask[:, element_idx]
                if key == "label":
                    values = labels[:, element_idx].clamp(0, self.config.num_labels - 1)
                else:
                    values = geometry[key][
                        :, element_idx
                    ] + self.config.bbox_token_offset(key)
                seq[:, token_idx] = torch.where(valid, values, seq[:, token_idx])
                attention_mask[:, token_idx] = valid
        lengths = mask[:, :max_elements].sum(dim=1) * len(self.config.var_order)
        for batch_idx, length in enumerate(lengths.tolist()):
            if length < seq.size(1):
                seq[batch_idx, length] = self.config.eos_token_id
                attention_mask[batch_idx, length] = True
        bos = labels.new_full((batch, 1), self.config.bos_token_id)
        bos_mask = torch.ones((batch, 1), dtype=torch.bool, device=labels.device)
        return BatchEncoding(
            {
                "input_ids": torch.cat([bos, seq], dim=1),
                "attention_mask": torch.cat([bos_mask, attention_mask], dim=1),
            }
        )

    def decode_layout(
        self, sequences: Int[torch.Tensor, "batch tokens"]
    ) -> dict[str, Shaped[torch.Tensor, "..."]]:
        """Decode RALF token ids to normalized layout tensors.

        Args:
            sequences: Generated token ids, with or without a leading BOS.

        Returns:
            Dictionary containing `bbox`, `labels`, and `mask`.
        """
        if sequences.ndim != 2:
            raise ValueError("sequences must have shape (B,T)")

        if sequences.size(1) and torch.all(sequences[:, 0] == self.config.bos_token_id):
            sequences = sequences[:, 1:]
        usable = sequences[:, : self.config.max_token_length]
        batch = usable.size(0)
        padded = usable.new_full(
            (batch, self.config.max_token_length),
            self.config.pad_token_id,
        )
        padded[:, : usable.size(1)] = usable
        tokens = padded.reshape(
            batch, self.config.max_seq_length, len(self.config.var_order)
        )
        labels = torch.zeros(
            (batch, self.config.max_seq_length),
            dtype=torch.long,
            device=sequences.device,
        )
        bbox_parts = {
            key: torch.zeros_like(labels, dtype=torch.float32) for key in GEO_KEYS
        }
        mask = torch.ones_like(labels, dtype=torch.bool)
        for var_idx, key in enumerate(self.config.var_order):
            values = tokens[..., var_idx]
            if key == "label":
                labels = values.clamp(0, self.config.num_labels - 1)
                mask &= values.lt(self.config.num_labels)
                eos_seen = torch.cumsum(values.eq(self.config.eos_token_id), dim=1) > 0
                mask &= ~eos_seen
            else:
                local = values - self.config.bbox_token_offset(key)
                mask &= (local >= 0) & (local < self.config.num_bin)
                bbox_parts[key] = self._dequantize(local)
        bbox = torch.stack(
            (
                bbox_parts["center_x"],
                bbox_parts["center_y"],
                bbox_parts["width"],
                bbox_parts["height"],
            ),
            dim=-1,
        ).clamp(0.0, 1.0)
        labels = torch.where(mask, labels, torch.zeros_like(labels))
        bbox = torch.where(mask.unsqueeze(-1), bbox, torch.zeros_like(bbox))
        return {"bbox": bbox, "labels": labels, "mask": mask}

    def token_mask(
        self, device: torch.device | None = None
    ) -> Bool[torch.Tensor, "tokens vocab"]:
        """Return valid-token masks by sequence position."""
        masks: list[Bool[torch.Tensor, "vocab"]] = []
        for _ in range(self.config.max_seq_length):
            for key in self.config.var_order:
                mask = torch.zeros(
                    self.config.vocab_size, dtype=torch.bool, device=device
                )
                if key == "label":
                    mask[: self.config.num_labels] = True
                    mask[self.config.eos_token_id] = True
                    mask[self.config.pad_token_id] = True
                else:
                    start = self.config.bbox_token_offset(key)
                    mask[start : start + self.config.num_bin] = True
                    mask[self.config.eos_token_id] = True
                    mask[self.config.pad_token_id] = True
                masks.append(mask)
        return torch.stack(masks, dim=0)

vocab_size property

vocab_size: int

Return total vocabulary size.

__init__

__init__(
    config: RalfConfig | None = None,
    tokenizer_config_file: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> None

Initialize tokenizer metadata and synthetic token strings.

Source code in models/ralf/src/ralf/tokenization_ralf.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
def __init__(
    self,
    config: RalfConfig | None = None,
    tokenizer_config_file: str | None = None,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Initialize tokenizer metadata and synthetic token strings."""
    if config is None and tokenizer_config_file is not None:
        with Path(tokenizer_config_file).open() as f:
            config = RalfConfig(**json.load(f)["config"])
    if config is None:
        raise ValueError("RalfLayoutTokenizer requires an explicit config")

    self.config = config
    self._token2id = self._build_vocab()
    self._id2token = {idx: token for token, idx in self._token2id.items()}
    kwargs.setdefault("pad_token", "[pad]")
    kwargs.setdefault("bos_token", "[bos]")
    kwargs.setdefault("eos_token", "[eos]")
    kwargs.setdefault("unk_token", "[unk]")
    kwargs.setdefault("model_max_length", self.config.max_token_length + 1)
    kwargs.setdefault("clean_up_tokenization_spaces", False)
    super().__init__(
        **kwargs,
    )

get_vocab

get_vocab() -> dict[str, int]

Return synthetic token strings mapped to ids.

Source code in models/ralf/src/ralf/tokenization_ralf.py
74
75
76
def get_vocab(self) -> dict[str, int]:
    """Return synthetic token strings mapped to ids."""
    return dict(self._token2id)

convert_tokens_to_string

convert_tokens_to_string(tokens: list[str]) -> str

Join synthetic layout tokens.

Source code in models/ralf/src/ralf/tokenization_ralf.py
101
102
103
def convert_tokens_to_string(self, tokens: list[str]) -> str:
    """Join synthetic layout tokens."""
    return " ".join(tokens)

save_vocabulary

save_vocabulary(
    save_directory: str, filename_prefix: str | None = None
) -> tuple[str, ...]

Save tokenizer metadata for Hub-compatible loading.

Source code in models/ralf/src/ralf/tokenization_ralf.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def save_vocabulary(
    self, save_directory: str, filename_prefix: str | None = None
) -> tuple[str, ...]:
    """Save tokenizer metadata for Hub-compatible loading."""
    out_dir = Path(save_directory)
    out_dir.mkdir(parents=True, exist_ok=True)
    name = (
        TOKENIZER_CONFIG_FILE
        if filename_prefix is None
        else f"{filename_prefix}-{TOKENIZER_CONFIG_FILE}"
    )
    path = out_dir / name
    with path.open("w") as f:
        json.dump({"config": self.config.to_dict()}, f, indent=2, sort_keys=True)
    return (str(path),)

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    legacy_format: bool | None = None,
    filename_prefix: str | None = None,
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> tuple[str, ...]

Save tokenizer files and the paired RalfConfig.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Output directory.

required
legacy_format bool | None

Standard tokenizer save flag.

None
filename_prefix str | None

Optional filename prefix.

None
push_to_hub bool

Whether to push through Hugging Face Hub helpers.

False
kwargs str | int | float | bool | None

Reserved tokenizer save arguments.

{}

Returns:

Type Description
tuple[str, ...]

Written tokenizer file paths.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    legacy_format: bool | None = None,
    filename_prefix: str | None = None,
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> tuple[str, ...]:
    """Save tokenizer files and the paired `RalfConfig`.

    Args:
        save_directory: Output directory.
        legacy_format: Standard tokenizer save flag.
        filename_prefix: Optional filename prefix.
        push_to_hub: Whether to push through Hugging Face Hub helpers.
        kwargs: Reserved tokenizer save arguments.

    Returns:
        Written tokenizer file paths.
    """
    paths = super().save_pretrained(
        save_directory,
        legacy_format=legacy_format,
        filename_prefix=filename_prefix,
        push_to_hub=push_to_hub,
        **kwargs,
    )
    self.config.save_pretrained(save_directory)
    return paths

from_pretrained classmethod

from_pretrained(
    pretrained_model_name_or_path: str | PathLike[str],
    *inputs: str,
    config: RalfConfig | None = None,
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
) -> "RalfLayoutTokenizer"

Load tokenizer metadata from a checkpoint directory.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str | PathLike[str],
    *inputs: str,
    config: RalfConfig | None = None,
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
) -> "RalfLayoutTokenizer":
    """Load tokenizer metadata from a checkpoint directory."""
    if config is None:
        config = RalfConfig.from_pretrained(pretrained_model_name_or_path)
    loaded = super().from_pretrained(
        pretrained_model_name_or_path,
        *inputs,
        cache_dir=cache_dir,
        force_download=force_download,
        local_files_only=local_files_only,
        token=token,
        revision=revision,
        config=config,
    )
    return cast("RalfLayoutTokenizer", loaded)

encode_layout

encode_layout(
    *,
    labels: Int[Tensor, "batch elements"],
    bbox: Float[Tensor, "batch elements 4"],
    mask: Bool[Tensor, "batch elements"] | None = None,
) -> BatchEncoding

Encode public normalized center xywh layouts to RALF tokens.

Parameters:

Name Type Description Default
labels Int[Tensor, 'batch elements']

Dataset-local integer labels.

required
bbox Float[Tensor, 'batch elements 4']

Normalized center xywh boxes.

required
mask Bool[Tensor, 'batch elements'] | None

Valid-element mask. If omitted, every element is valid.

None

Returns:

Type Description
BatchEncoding

BatchEncoding with input_ids and attention_mask.

Raises:

Type Description
ValueError

If tensor ranks are invalid.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
def encode_layout(
    self,
    *,
    labels: Int[torch.Tensor, "batch elements"],
    bbox: Float[torch.Tensor, "batch elements 4"],
    mask: Bool[torch.Tensor, "batch elements"] | None = None,
) -> BatchEncoding:
    """Encode public normalized center `xywh` layouts to RALF tokens.

    Args:
        labels: Dataset-local integer labels.
        bbox: Normalized center `xywh` boxes.
        mask: Valid-element mask. If omitted, every element is valid.

    Returns:
        BatchEncoding with `input_ids` and `attention_mask`.

    Raises:
        ValueError: If tensor ranks are invalid.
    """
    if labels.ndim != 2 or bbox.ndim != 3 or bbox.shape[-1] != 4:
        raise ValueError("labels must be (B,S) and bbox must be (B,S,4)")

    if mask is None:
        mask = torch.ones_like(labels, dtype=torch.bool)
    batch, elements = labels.shape
    max_elements = min(elements, self.config.max_seq_length)
    seq = labels.new_full(
        (batch, self.config.max_token_length),
        self.config.pad_token_id,
    )
    attention_mask = torch.zeros_like(seq, dtype=torch.bool)
    geometry = {
        "center_x": self._quantize(bbox[..., 0]),
        "center_y": self._quantize(bbox[..., 1]),
        "width": self._quantize(bbox[..., 2]),
        "height": self._quantize(bbox[..., 3]),
    }
    for element_idx in range(max_elements):
        for var_idx, key in enumerate(self.config.var_order):
            token_idx = element_idx * len(self.config.var_order) + var_idx
            valid = mask[:, element_idx]
            if key == "label":
                values = labels[:, element_idx].clamp(0, self.config.num_labels - 1)
            else:
                values = geometry[key][
                    :, element_idx
                ] + self.config.bbox_token_offset(key)
            seq[:, token_idx] = torch.where(valid, values, seq[:, token_idx])
            attention_mask[:, token_idx] = valid
    lengths = mask[:, :max_elements].sum(dim=1) * len(self.config.var_order)
    for batch_idx, length in enumerate(lengths.tolist()):
        if length < seq.size(1):
            seq[batch_idx, length] = self.config.eos_token_id
            attention_mask[batch_idx, length] = True
    bos = labels.new_full((batch, 1), self.config.bos_token_id)
    bos_mask = torch.ones((batch, 1), dtype=torch.bool, device=labels.device)
    return BatchEncoding(
        {
            "input_ids": torch.cat([bos, seq], dim=1),
            "attention_mask": torch.cat([bos_mask, attention_mask], dim=1),
        }
    )

decode_layout

decode_layout(
    sequences: Int[Tensor, "batch tokens"],
) -> dict[str, Shaped[torch.Tensor, "..."]]

Decode RALF token ids to normalized layout tensors.

Parameters:

Name Type Description Default
sequences Int[Tensor, 'batch tokens']

Generated token ids, with or without a leading BOS.

required

Returns:

Type Description
dict[str, Shaped[Tensor, '...']]

Dictionary containing bbox, labels, and mask.

Source code in models/ralf/src/ralf/tokenization_ralf.py
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
def decode_layout(
    self, sequences: Int[torch.Tensor, "batch tokens"]
) -> dict[str, Shaped[torch.Tensor, "..."]]:
    """Decode RALF token ids to normalized layout tensors.

    Args:
        sequences: Generated token ids, with or without a leading BOS.

    Returns:
        Dictionary containing `bbox`, `labels`, and `mask`.
    """
    if sequences.ndim != 2:
        raise ValueError("sequences must have shape (B,T)")

    if sequences.size(1) and torch.all(sequences[:, 0] == self.config.bos_token_id):
        sequences = sequences[:, 1:]
    usable = sequences[:, : self.config.max_token_length]
    batch = usable.size(0)
    padded = usable.new_full(
        (batch, self.config.max_token_length),
        self.config.pad_token_id,
    )
    padded[:, : usable.size(1)] = usable
    tokens = padded.reshape(
        batch, self.config.max_seq_length, len(self.config.var_order)
    )
    labels = torch.zeros(
        (batch, self.config.max_seq_length),
        dtype=torch.long,
        device=sequences.device,
    )
    bbox_parts = {
        key: torch.zeros_like(labels, dtype=torch.float32) for key in GEO_KEYS
    }
    mask = torch.ones_like(labels, dtype=torch.bool)
    for var_idx, key in enumerate(self.config.var_order):
        values = tokens[..., var_idx]
        if key == "label":
            labels = values.clamp(0, self.config.num_labels - 1)
            mask &= values.lt(self.config.num_labels)
            eos_seen = torch.cumsum(values.eq(self.config.eos_token_id), dim=1) > 0
            mask &= ~eos_seen
        else:
            local = values - self.config.bbox_token_offset(key)
            mask &= (local >= 0) & (local < self.config.num_bin)
            bbox_parts[key] = self._dequantize(local)
    bbox = torch.stack(
        (
            bbox_parts["center_x"],
            bbox_parts["center_y"],
            bbox_parts["width"],
            bbox_parts["height"],
        ),
        dim=-1,
    ).clamp(0.0, 1.0)
    labels = torch.where(mask, labels, torch.zeros_like(labels))
    bbox = torch.where(mask.unsqueeze(-1), bbox, torch.zeros_like(bbox))
    return {"bbox": bbox, "labels": labels, "mask": mask}

token_mask

token_mask(
    device: device | None = None,
) -> Bool[torch.Tensor, "tokens vocab"]

Return valid-token masks by sequence position.

Source code in models/ralf/src/ralf/tokenization_ralf.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def token_mask(
    self, device: torch.device | None = None
) -> Bool[torch.Tensor, "tokens vocab"]:
    """Return valid-token masks by sequence position."""
    masks: list[Bool[torch.Tensor, "vocab"]] = []
    for _ in range(self.config.max_seq_length):
        for key in self.config.var_order:
            mask = torch.zeros(
                self.config.vocab_size, dtype=torch.bool, device=device
            )
            if key == "label":
                mask[: self.config.num_labels] = True
                mask[self.config.eos_token_id] = True
                mask[self.config.pad_token_id] = True
            else:
                start = self.config.bbox_token_offset(key)
                mask[start : start + self.config.num_bin] = True
                mask[self.config.eos_token_id] = True
                mask[self.config.pad_token_id] = True
            masks.append(mask)
    return torch.stack(masks, dim=0)