diff --git a/ignition/cli/__init__.py b/ignition/cli/__init__.py index b1bc7775b..591014bc1 100644 --- a/ignition/cli/__init__.py +++ b/ignition/cli/__init__.py @@ -363,11 +363,11 @@ def parse_args(argv=None, *, recipes=(), prog="ignition"): def main(argv=None, *, recipes=(), prog="ignition", source_roots=()) -> int: from ignition.preparation.source_identity import source_roots as bind_source_roots - from ignition.registry import active_recipes + from ignition.registry import active_prog, active_recipes recipes = tuple(recipes) try: - with active_recipes(recipes), bind_source_roots(source_roots): + with active_recipes(recipes), active_prog(prog), bind_source_roots(source_roots): args = parse_args(argv, recipes=recipes, prog=prog) return args.handler(args) or 0 except FlareError as error: diff --git a/ignition/components/state.py b/ignition/components/state.py index 9908c10c5..0f7bd953c 100644 --- a/ignition/components/state.py +++ b/ignition/components/state.py @@ -109,9 +109,9 @@ def gather_rows(source, rows, destination): @triton.jit def _gather_rows(Source, Rows, Output, SS: tl.constexpr, OS: tl.constexpr, RS: tl.constexpr, WIDTH: tl.constexpr, BLOCK: tl.constexpr): - row = tl.program_id(0) - columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) - selected = tl.load(Rows + row * RS) + row = tl.program_id(0).to(tl.int64) + columns = (tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)).to(tl.int64) + selected = tl.load(Rows + row * RS).to(tl.int64) value = tl.load(Source + selected * SS + columns, columns < WIDTH, other=0) tl.store(Output + row * OS + columns, value, columns < WIDTH) @@ -137,9 +137,9 @@ def _gather_rows_three(First, Second, Third, Rows, OutFirst, OutSecond, OutThird FS: tl.constexpr, SS: tl.constexpr, TS: tl.constexpr, FO: tl.constexpr, SO: tl.constexpr, TO: tl.constexpr, RS: tl.constexpr, FW: tl.constexpr, SW: tl.constexpr, TW: tl.constexpr, BLOCK: tl.constexpr): - row = tl.program_id(0) - columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) - selected = tl.load(Rows + row * RS) + row = tl.program_id(0).to(tl.int64) + columns = (tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)).to(tl.int64) + selected = tl.load(Rows + row * RS).to(tl.int64) first = tl.load(First + selected * FS + columns, columns < FW, other=0) second = tl.load(Second + selected * SS + columns, columns < SW, other=0) third = tl.load(Third + selected * TS + columns, columns < TW, other=0) @@ -162,26 +162,43 @@ def save_hidden(source, destination, slots, active): destination[slots[selected]] = source[selected] -def scatter_rows(source, rows, destination, active): - """Store active rows at unique request slots, preserving all other rows.""" +def scatter_rows(source, rows, destination, active, *, memory_capacity=None, allow_zero=False): + """Store active rows at unique destination slots, preserving all other rows. + + ``allow_zero`` defaults to False so continuation-state writes never mutate + the reserved null slot 0. Pass ``memory_capacity`` (for example + ``pool.memory_capacity``) when scattering into dynamically grown + ``STATE_ROWS`` storage so runtime writes honor Helios's live slot limit. + """ source = source.view(source.shape[0], -1) output = destination.view(destination.shape[0], -1) + if memory_capacity is not None: + if (not isinstance(memory_capacity, torch.Tensor) or memory_capacity.ndim < 1 + or memory_capacity.numel() < 1 or memory_capacity.dtype != torch.int64 + or memory_capacity.device != output.device): + raise ValueError("memory_capacity must be a nonempty int64 tensor on the destination device") if source.is_cuda: + capacity_tensor = rows if memory_capacity is None else memory_capacity torch.library.wrap_triton(_scatter_rows)[(source.shape[0], triton.cdiv(source.shape[1], 1024))]( - source, rows, output, active, source.stride(0), source.stride(1), output.stride(0), - source.shape[1], output.shape[0], 1024) + source, rows, output, active, capacity_tensor, source.stride(0), source.stride(1), output.stride(0), + source.shape[1], output.shape[0], 1024, memory_capacity is not None, bool(allow_zero)) else: - selected = active.bool() & (rows >= 0) & (rows < output.shape[0]) + limit = output.shape[0] if memory_capacity is None else int(memory_capacity[0].item()) + in_bounds = (rows >= 0) if allow_zero else (rows > 0) + selected = active.bool() & in_bounds & (rows < limit) output[rows[selected], :source.shape[1]] = source[selected] @triton.jit -def _scatter_rows(Source, Rows, Output, Active, SS: tl.constexpr, CS: tl.constexpr, - OS: tl.constexpr, WIDTH: tl.constexpr, SLOTS: tl.constexpr, BLOCK: tl.constexpr): - row = tl.program_id(0) - columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) - selected = tl.load(Rows + row) - active = (tl.load(Active + row) != 0) & (selected >= 0) & (selected < SLOTS) +def _scatter_rows(Source, Rows, Output, Active, MemoryCapacity, SS: tl.constexpr, CS: tl.constexpr, + OS: tl.constexpr, WIDTH: tl.constexpr, SLOTS: tl.constexpr, BLOCK: tl.constexpr, + HAS_CAPACITY: tl.constexpr, ALLOW_ZERO: tl.constexpr): + row = tl.program_id(0).to(tl.int64) + columns = (tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)).to(tl.int64) + selected = tl.load(Rows + row).to(tl.int64) + limit = tl.load(MemoryCapacity).to(tl.int64) if HAS_CAPACITY else SLOTS + in_bounds = (selected >= 0) if ALLOW_ZERO else (selected > 0) + active = (tl.load(Active + row) != 0) & in_bounds & (selected < limit) values = tl.load(Source + row * SS + columns * CS, active & (columns < WIDTH), other=0) tl.store(Output + selected * OS + columns, values, active & (columns < WIDTH)) @@ -189,10 +206,10 @@ def _scatter_rows(Source, Rows, Output, Active, SS: tl.constexpr, CS: tl.constex @triton.jit def _save_hidden(Source, Destination, Slots, Active, SS: tl.constexpr, DS: tl.constexpr, WIDTH: tl.constexpr, BLOCK: tl.constexpr): - row = tl.program_id(0) - slot = tl.load(Slots + row) + row = tl.program_id(0).to(tl.int64) + slot = tl.load(Slots + row).to(tl.int64) active = (tl.load(Active + row) != 0) & (slot > 0) - columns = tl.arange(0, BLOCK) + columns = tl.arange(0, BLOCK).to(tl.int64) value = tl.load(Source + row * SS + columns, active & (columns < WIDTH), other=0) tl.store(Destination + slot * DS + columns, value, active & (columns < WIDTH)) @@ -222,9 +239,9 @@ def _request_history(Counts, History, SavedCounts, SavedHistory, Requests, Sourc Count, Errors, MemoryCapacity, REQUESTS: tl.constexpr, CS: tl.constexpr, SS: tl.constexpr, HS: tl.constexpr, SHS: tl.constexpr, HAS_HISTORY: tl.constexpr, SNAPSHOT: tl.constexpr): - command = tl.program_id(0) - slot = tl.load(Requests + command) - row = tl.load(Sources + command) if SNAPSHOT else tl.load(Destinations + command) + command = tl.program_id(0).to(tl.int64) + slot = tl.load(Requests + command).to(tl.int64) + row = (tl.load(Sources + command) if SNAPSHOT else tl.load(Destinations + command)).to(tl.int64) valid = (command < tl.load(Count)) & (tl.load(Errors + command) == 0) valid &= (slot >= 0) & (slot < REQUESTS) & (row > 0) & (row < tl.load(MemoryCapacity)) if SNAPSHOT: @@ -234,7 +251,7 @@ def _request_history(Counts, History, SavedCounts, SavedHistory, Requests, Sourc value = tl.load(SavedCounts + row * SS, valid, other=0) tl.store(Counts + slot * CS, value, valid) if HAS_HISTORY: - columns = tl.arange(0, 2) + columns = tl.arange(0, 2).to(tl.int64) if SNAPSHOT: value = tl.load(History + slot * HS + columns, valid, other=0) tl.store(SavedHistory + row * SHS + columns, value, valid) diff --git a/ignition/preparation/frontend.py b/ignition/preparation/frontend.py index befb094d3..4cd348d2c 100644 --- a/ignition/preparation/frontend.py +++ b/ignition/preparation/frontend.py @@ -4,11 +4,14 @@ """Extract and validate the structural frontend fields consumed by Helios.""" -import json +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field import hashlib +import json import math from enum import IntEnum from pathlib import Path +from typing import Any class PromptEncoder(IntEnum): @@ -20,6 +23,49 @@ class PromptEncoder(IntEnum): TOKEN_FIELDS = ("bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token") +IMAGE_PROFILES = frozenset({ + "padded_grid", + "glm", + "radio", + "moonvit", + "deepseek_row_major", + "deepseek4", + "qwen", + "mimo", +}) + +_EMPTY_IMAGE_PROFILES = frozenset({"padded_grid", "glm", "radio", "moonvit", "deepseek4"}) + + +@dataclass(frozen=True) +class ImageProcessorSpec: + """Recipe-owned checkpoint validation contract for a native Helios image profile.""" + + profile: str + label: str = "" + processor_fields: Mapping[str, Any] = field(default_factory=dict) + image_processor_key: str | None = None + image_processor_fields: Mapping[str, Any] = field(default_factory=dict) + image_processor_exact_keys: bool = False + image_processor_optional_fields: Mapping[str, Any] = field(default_factory=dict) + size_fields: Mapping[str, Any] = field(default_factory=dict) + model_fields: Mapping[str, Any] = field(default_factory=dict) + model_types: tuple[str, ...] = () + vision_fields: Mapping[str, Any] = field(default_factory=dict) + requires_preprocessor: bool = True + default_preprocessor: str = "preprocessor_config.json" + extract: Callable[[Mapping[str, Any], Mapping[str, Any]], dict[str, Any]] | None = None + + def __post_init__(self): + if self.profile not in IMAGE_PROFILES: + raise ValueError(f"unsupported image preprocessing profile {self.profile!r}") + if not isinstance(self.label, str): + raise TypeError("image processor spec label must be a string") + if self.image_processor_key is not None and not isinstance(self.image_processor_key, str): + raise TypeError("image_processor_key must be a string or None") + if any(not isinstance(item, str) or not item for item in self.model_types): + raise ValueError("model_types must contain nonempty strings") + def annotated_template_asset(source: bytes, patch_path: Path): """Insert message marks into exact checkpoint bytes, without bundling that source.""" @@ -89,118 +135,112 @@ def _expected(config, values, label): raise ValueError(f"unsupported {label} {key}") -def image_settings(config, model, profile, qwen_model_type="qwen4_exp"): - """Resolve the image settings the native frontend consumes for ``profile``. - - The Qwen profile serves two checkpoint families with one processor; ``qwen_model_type`` - is the ``model_type`` the preparing recipe requires of its checkpoint. - """ - if profile == "padded_grid": - # Inkling 2 ships the processor in processor_config.json; `size` is the token cell, not a resize target. - _expected(config, {"processor_class": "Inkling2Processor"}, "padded-grid processor") - image = config.get("image_processor") - expected = {"image_processor_type": "Inkling2ImageProcessor", "size": {"height": 40, "width": 40}, - "image_mean": [0.5] * 3, "image_std": [0.5] * 3, "rescale_factor": 1 / 255, - "do_rescale": True, "do_normalize": True, "do_convert_rgb": True} - if not isinstance(image, dict) or set(image) != set(expected): - raise ValueError("unsupported padded-grid image processor fields") - _expected(image, expected, "padded-grid image processor") - if model.get("model_type") not in ("inkling2", "inkling2_loop"): - raise ValueError("unsupported padded-grid model configuration model_type") - _expected(model["vision_config"], {"native_patch_size": 20, "adapter_merge_size": 2, - "posemb_grid_size": 32, "temporal_patch_size": 2}, "padded-grid vision configuration") - return {"padded_grid": {}} - if profile == "glm": - _expected(config, {"processor_class": "Glm5NextProcessor"}, "GLM processor") - image = config["image_processor"] - _expected(image, {"image_processor_type": "Glm5NextImageProcessor", "patch_size": 14, - "temporal_patch_size": 2, "merge_size": 2, "patch_expand_factor": 1, - "min_image_tokens": 16, "max_image_tokens": 8000, - "image_mean": [0.48145466, 0.4578275, 0.40821073], - "image_std": [0.26862954, 0.26130258, 0.27577711]}, "GLM image processor") - optional = {"resample": 3, "rescale_factor": 1 / 255, - "do_resize": True, "do_rescale": True, "do_normalize": True, "do_convert_rgb": True} - _expected(image, {key: value for key, value in optional.items() if key in image}, "GLM image processor") - _expected(model, {"model_type": "glm5_next", "image_token_id": 154854, "video_token_id": 154855}, - "GLM model configuration") - _expected(model["vision_config"], {"patch_size": 14, "temporal_patch_size": 2, - "spatial_merge_size": 2, "in_channels": 3}, "GLM vision configuration") - return {"glm": {}} - if profile == "radio": - _expected(config, {"image_processor_type": "NemotronH_Omni_Reasoning_V3ImageProcessor", - "patch_size": 16, "downsample_ratio": .5, "max_model_len": 16384, - "min_num_patches": 1024, "max_num_patches": 13312, - "norm_mean": [0.48145466, 0.4578275, 0.40821073], - "norm_std": [0.26862954, 0.26130258, 0.27577711]}, "RADIO image processor") - _expected(model, {"patch_size": 16, "downsample_ratio": .5, "ps_version": "v2", - "img_context_token_id": 18}, "RADIO image configuration") - _expected(model["vision_config"], {"max_img_size": 2048, "patch_size": 16}, "RADIO vision configuration") - return {"radio": {}} - if profile == "moonvit": - _expected(config["media_proc_cfg"], {"in_patch_limit": 65536, "patch_size": 14, - "image_mean": [0.5] * 3, "image_std": [0.5] * 3, "merge_kernel_size": 2, - "fixed_output_tokens": None, "patch_limit_on_one_side": 512, - "transparent_bg_fill_stage": "after_resize", "transparent_bg_config": { - "pattern": "chessboard", "chessboard_square_size": 8, - "chessboard_square_on_top_left": True, "chessboard_white_value": 255, - "chessboard_gray_value": 180}}, "MoonViT image processor") - _expected(model["vision_config"], {"patch_size": 14, "init_pos_emb_height": 64, - "init_pos_emb_width": 64, "pos_emb_interpolation_mode": "bilinear", - "merge_kernel_size": [2, 2]}, "MoonViT vision configuration") - return {"moonvit": {}} +def _qualified(label: str, noun: str) -> str: + return f"{label} {noun}" if label else noun + + +def _validate_positive_int(value: Any, name: str) -> int: + if type(value) is not int or value <= 0: + raise ValueError(f"unsupported image processor {name}") + return value + + +def _validate_uint32(value: Any, name: str) -> int: + if type(value) is not int or not 0 <= value < 2**32: + raise ValueError(f"invalid model {name}") + return value + + +def _validate_image_payload(profile: str, payload: Mapping[str, Any]) -> dict[str, Any]: + if not isinstance(payload, Mapping): + raise ValueError("image settings payload must be a mapping") + if profile in _EMPTY_IMAGE_PROFILES: + if payload: + raise ValueError(f"image profile {profile!r} takes no payload fields") + return {} if profile == "deepseek_row_major": - vision = model["vision_config"] - _expected(vision, {"patch_size": 14, "downsample_ratio": 3, "max_image_tokens": 1024, - "min_pixels": 295936, "max_wh_ratio": None}, "DeepSeek row-major vision configuration") - return {profile: dict(min_pixels=vision["min_pixels"], max_tokens=vision["max_image_tokens"])} - if profile == "deepseek4": - _expected(config, {"image_processor_type": "DeepSeekV4ImageProcessor", "patch_size": 14, - "merge_size": 3, "max_image_tokens": 384, "min_pixels": 147456, - "max_width_height_ratio": 8}, "DeepSeek image processor") - _expected(model, {"vision_patch_size": 14, "vision_downsample_ratio": 3, - "vision_max_n_token": 384, "vision_min_pixels": 147456, - "vision_max_wh_ratio": 8}, "DeepSeek vision configuration") - return {"deepseek4": {}} - if profile not in ("qwen", "mimo"): - raise ValueError("unsupported image preprocessing profile") - qwen = profile == "qwen" - if qwen: - _expected(config, {"image_mean": [0.5] * 3, "image_std": [0.5] * 3}, "image processor") - _expected(config, {"processor_class": "Qwen3VLProcessor" if qwen else "Qwen2_5_VLProcessor", - "image_processor_type": "Qwen2VLImageProcessorFast" if qwen else "Qwen2VLImageProcessor", - "patch_size": 16, "temporal_patch_size": 2, "merge_size": 2}, "image processor") - optional = {"resample": 3, "rescale_factor": 1 / 255, - "do_resize": True, "do_rescale": True, "do_normalize": True, "do_convert_rgb": True} - _expected(config, {key: value for key, value in optional.items() if key in config}, "image processor") - _expected(model, {"model_type": qwen_model_type if qwen else "mimo_v2"}, "model configuration") - vision = model["vision_config"] - _expected(vision, {"patch_size": 16, "temporal_patch_size": 2, "spatial_merge_size": 2}, "vision configuration") - if qwen: - _expected(vision, {"in_channels": 3, "num_position_embeddings": 2304}, "vision configuration") - _expected(config["size"], {"shortest_edge": 65536, "longest_edge": 16777216}, "resize area") - result = dict(min_pixels=65536, max_pixels=16777216, position_side=48) - for name in ("image_token_id", "video_token_id"): - value = model[name] - if type(value) is not int or not 0 <= value < 2**32: - raise ValueError(f"invalid model {name}") - result[name] = value - else: - # MiMo checkpoints publish their own resize area and normalization; the native frontend - # consumes the packaged values, so preparation validates their form rather than fixing them. - _expected(model, {"image_token_id": 151655}, "model configuration") - result = dict(min_pixels=config.get("min_pixels"), max_pixels=config.get("max_pixels"), - image_mean=config.get("image_mean"), image_std=config.get("image_std")) - if (any(type(result[key]) is not int for key in ("min_pixels", "max_pixels")) - or not 0 < result["min_pixels"] <= result["max_pixels"]): + expected_keys = {"min_pixels", "max_tokens"} + if set(payload) != expected_keys: + raise ValueError("unsupported deepseek_row_major image payload fields") + return { + "min_pixels": _validate_positive_int(payload["min_pixels"], "min_pixels"), + "max_tokens": _validate_positive_int(payload["max_tokens"], "max_tokens"), + } + if profile == "qwen": + expected_keys = {"min_pixels", "max_pixels", "position_side", "image_token_id", "video_token_id"} + if set(payload) != expected_keys: + raise ValueError("unsupported qwen image payload fields") + min_pixels = _validate_positive_int(payload["min_pixels"], "resize area") + max_pixels = _validate_positive_int(payload["max_pixels"], "resize area") + if min_pixels > max_pixels: + raise ValueError("unsupported image processor resize area") + return { + "min_pixels": min_pixels, + "max_pixels": max_pixels, + "position_side": _validate_positive_int(payload["position_side"], "position_side"), + "image_token_id": _validate_uint32(payload["image_token_id"], "image_token_id"), + "video_token_id": _validate_uint32(payload["video_token_id"], "video_token_id"), + } + if profile == "mimo": + expected_keys = {"min_pixels", "max_pixels", "image_mean", "image_std"} + if set(payload) != expected_keys: + raise ValueError("unsupported mimo image payload fields") + min_pixels = payload["min_pixels"] + max_pixels = payload["max_pixels"] + if (type(min_pixels) is not int or type(max_pixels) is not int + or not 0 < min_pixels <= max_pixels): raise ValueError("unsupported image processor resize area") + result: dict[str, Any] = {"min_pixels": min_pixels, "max_pixels": max_pixels} for key in ("image_mean", "image_std"): - values = result[key] - if (not isinstance(values, list) or len(values) != 3 + values = payload[key] + if (not isinstance(values, (list, tuple)) or len(values) != 3 or any(type(v) not in (int, float) or not math.isfinite(v) for v in values) - or key == "image_std" and any(v <= 0 for v in values)): + or (key == "image_std" and any(v <= 0 for v in values))): raise ValueError(f"unsupported image processor {key}") result[key] = [float(v) for v in values] - return {profile: result} + return result + raise ValueError("unsupported image preprocessing profile") + + +def image_settings(config, model, spec: ImageProcessorSpec): + """Validate checkpoint image metadata against a recipe-owned ``ImageProcessorSpec``.""" + if not isinstance(spec, ImageProcessorSpec): + raise TypeError("image_settings requires an ImageProcessorSpec") + if spec.processor_fields: + _expected(config, spec.processor_fields, _qualified(spec.label, "processor")) + image = config if spec.image_processor_key is None else config.get(spec.image_processor_key) + needs_image = bool( + spec.image_processor_fields + or spec.image_processor_exact_keys + or spec.image_processor_optional_fields + or spec.size_fields + ) + if needs_image: + if not isinstance(image, dict): + raise ValueError(f"unsupported {_qualified(spec.label, 'image processor')} fields") + if spec.image_processor_exact_keys and set(image) != set(spec.image_processor_fields): + raise ValueError(f"unsupported {_qualified(spec.label, 'image processor')} fields") + if spec.image_processor_fields: + _expected(image, spec.image_processor_fields, _qualified(spec.label, "image processor")) + if spec.image_processor_optional_fields: + present = {key: value for key, value in spec.image_processor_optional_fields.items() if key in image} + _expected(image, present, _qualified(spec.label, "image processor")) + if spec.size_fields: + size = image.get("size") + if not isinstance(size, dict): + raise ValueError("unsupported resize area") + _expected(size, spec.size_fields, "resize area") + if spec.model_types and model.get("model_type") not in spec.model_types: + raise ValueError(f"unsupported {_qualified(spec.label, 'model configuration')} model_type") + if spec.model_fields: + _expected(model, spec.model_fields, _qualified(spec.label, "model configuration")) + if spec.vision_fields: + vision = model.get("vision_config") + if not isinstance(vision, dict): + raise ValueError(f"unsupported {_qualified(spec.label, 'vision configuration')}") + _expected(vision, spec.vision_fields, _qualified(spec.label, "vision configuration")) + raw_payload = {} if spec.extract is None else spec.extract(image, model) + return {spec.profile: _validate_image_payload(spec.profile, raw_payload)} def _native_image_placeholder(snapshot, model, encoder): @@ -220,11 +260,13 @@ def _native_image_placeholder(snapshot, model, encoder): return token_id -def prepare_frontend(snapshot, *, eos_token_ids, image_profile=None, preprocessor=None, - prompt_encoder=PromptEncoder.PROMPT_JINJA, qwen_model_type="qwen4_exp"): - """Resolve checkpoint structure during preparation; sampling is recipe-owned.""" +def prepare_frontend(snapshot, *, eos_token_ids, image_spec: ImageProcessorSpec | None = None, + preprocessor=None, prompt_encoder=PromptEncoder.PROMPT_JINJA): + """Resolve checkpoint structure during preparation; sampling and image specs are recipe-owned.""" if not isinstance(prompt_encoder, PromptEncoder): raise ValueError("prompt_encoder must be a PromptEncoder") + if image_spec is not None and not isinstance(image_spec, ImageProcessorSpec): + raise TypeError("image_spec must be an ImageProcessorSpec") snapshot = Path(snapshot) if type(eos_token_ids) is int: eos_token_ids = [eos_token_ids] @@ -236,16 +278,19 @@ def prepare_frontend(snapshot, *, eos_token_ids, image_profile=None, preprocesso "eos_token_ids": eos_token_ids} if prompt_encoder != PromptEncoder.PROMPT_JINJA: result["prompt_encoder"] = int(prompt_encoder) - if image_profile is not None: + if image_spec is not None: + model = json.loads((snapshot / "config.json").read_text()) expected_profile = {PromptEncoder.DEEPSEEK_V4: "deepseek4", PromptEncoder.DEEPSEEK_V41: "deepseek_row_major"}.get(prompt_encoder) if expected_profile is not None: - if image_profile != expected_profile: + if image_spec.profile != expected_profile: raise ValueError("image profile differs from the prompt encoder") result["image_placeholder_token_id"] = _native_image_placeholder( - snapshot, json.loads((snapshot / "config.json").read_text()), prompt_encoder) - path = snapshot / "preprocessor_config.json" if preprocessor is None else Path(preprocessor) - result["image"] = image_settings({} if image_profile == "deepseek_row_major" else json.loads(path.read_text()), - json.loads((snapshot / "config.json").read_text()), image_profile, - qwen_model_type=qwen_model_type) + snapshot, model, prompt_encoder) + if not image_spec.requires_preprocessor and preprocessor is None: + processor_config = {} + else: + path = snapshot / image_spec.default_preprocessor if preprocessor is None else Path(preprocessor) + processor_config = json.loads(path.read_text()) + result["image"] = image_settings(processor_config, model, image_spec) return result diff --git a/ignition/preparation/rebuild_manifest.py b/ignition/preparation/rebuild_manifest.py index 733eae1d1..b14cead44 100644 --- a/ignition/preparation/rebuild_manifest.py +++ b/ignition/preparation/rebuild_manifest.py @@ -228,11 +228,12 @@ def _members(value): return [(f'.{field.name}', getattr(value, field.name)) for field in fields(value)] -def reproduction_arguments(model, plan, *, compiled_forwards=None, multi_host=None): - """Build canonical `ignition export` arguments reproducing `plan` without host-local paths.""" +def reproduction_arguments(model, plan, *, compiled_forwards=None, multi_host=None, prog=None): + """Build canonical ` export` arguments reproducing `plan` without host-local paths.""" from dataclasses import replace from pathlib import Path from ignition.parameters import ParameterContext + from ignition.registry import current_prog if model.directory is not None: target = Path(model.directory).name @@ -258,7 +259,8 @@ def reproduction_arguments(model, plan, *, compiled_forwards=None, multi_host=No gpus=plan.gpus, world_size=plan.world_size, ) - return ['ignition', 'export', target, *params.reproduction_args(context)] + program = current_prog() if prog is None else prog + return [program, 'export', target, *params.reproduction_args(context)] SCOPE_DEPLOYMENT = 'PREPARATION_PARAMETER_SCOPE_DEPLOYMENT' @@ -283,7 +285,7 @@ def _preparation_value(value): raise TypeError(f'unsupported preparation parameter value type: {type(value).__name__}') -def from_plan(model, plan, *, compiled_forwards=None, multi_host=None): +def from_plan(model, plan, *, compiled_forwards=None, multi_host=None, prog=None): """Build a `PreparationManifest` exclusively from `plan.parameters` and checkpoint provenance.""" from dataclasses import replace from ignition.parameters import ParameterContext, ParameterScope @@ -329,7 +331,8 @@ def from_plan(model, plan, *, compiled_forwards=None, multi_host=None): 'checkpoint_revision': plan.checkpoint.revision if model.directory is None else '', 'local_checkpoint': model.directory is not None, 'reproduction_args': reproduction_arguments( - model, plan, compiled_forwards=params.compiled_forwards, multi_host=params.multi_host + model, plan, compiled_forwards=params.compiled_forwards, multi_host=params.multi_host, + prog=prog, ), 'parameters': parameters, } diff --git a/ignition/registry.py b/ignition/registry.py index 29185f91b..d63f38456 100644 --- a/ignition/registry.py +++ b/ignition/registry.py @@ -24,6 +24,9 @@ _ACTIVE_RECIPES: contextvars.ContextVar[tuple[Recipe, ...]] = contextvars.ContextVar( "flare_active_recipes", default=() ) +_ACTIVE_PROG: contextvars.ContextVar[str] = contextvars.ContextVar( + "flare_active_prog", default="ignition" +) def current_recipes() -> tuple[Recipe, ...]: @@ -31,6 +34,11 @@ def current_recipes() -> tuple[Recipe, ...]: return _ACTIVE_RECIPES.get() +def current_prog() -> str: + """Return the CLI program name bound to the current invocation context.""" + return _ACTIVE_PROG.get() + + @contextmanager def active_recipes(recipes: Sequence[Recipe]): """Bind `recipes` for the duration of a CLI invocation or test scope.""" @@ -41,6 +49,18 @@ def active_recipes(recipes: Sequence[Recipe]): _ACTIVE_RECIPES.reset(token) +@contextmanager +def active_prog(prog: str): + """Bind the CLI program name for rebuild metadata during a CLI invocation or test scope.""" + if not isinstance(prog, str) or not prog.strip(): + raise ValueError("CLI program name must be a nonempty string") + token = _ACTIVE_PROG.set(prog) + try: + yield + finally: + _ACTIVE_PROG.reset(token) + + def snapshot_directory(hub_cache: Path, checkpoint: Checkpoint) -> Path: """Resolve a checkpoint's local source or pinned hub-cache directory.""" if Path(checkpoint.repository).is_absolute(): diff --git a/tests/cli/test_parameters.py b/tests/cli/test_parameters.py index 94aede66e..253112896 100644 --- a/tests/cli/test_parameters.py +++ b/tests/cli/test_parameters.py @@ -359,6 +359,13 @@ def test_pure_manifest_emission_and_reproduction_args_round_trip(monkeypatch): reparsed_plan = planning.plan(recipe, recipe.checkpoints[0], (_gpu(0),), selected=(0,), parameters=reparsed_params) repro_manifest = rebuild_manifest.from_plan(SimpleNamespace(directory=None), reparsed_plan) assert repro_manifest["parameters"] == manifest["parameters"] + assert manifest["reproduction_args"][0] == "ignition" + from ignition.registry import active_prog + + with active_prog("ignition-jetson"): + jetson_manifest = rebuild_manifest.from_plan(SimpleNamespace(directory=None), plan) + assert jetson_manifest["reproduction_args"][0] == "ignition-jetson" + assert jetson_manifest["reproduction_args"][1:] == manifest["reproduction_args"][1:] def test_recipe_declared_speculative_method_metadata_cli_display_and_planning(): diff --git a/tests/components/test_state.py b/tests/components/test_state.py index 1bf9f3878..32a8ef357 100644 --- a/tests/components/test_state.py +++ b/tests/components/test_state.py @@ -87,3 +87,65 @@ def test_request_row_scatter_and_prefix_gather_preserve_unselected_data(): assert torch.equal(verification, proposals[[1, 0], :2]) scatter_rows(proposals, torch.tensor([-1, 0]), retained, torch.tensor([True, False])) assert retained[0].eq(-1).all() + # By default, scatter_rows protects null continuation slot 0 even when active. + scatter_rows(proposals, torch.tensor([0, 2]), retained, torch.tensor([True, True])) + assert retained[0].eq(-1).all() + assert torch.equal(retained[2, :3], proposals[1]) + # Explicit allow_zero=True permits 0-indexed non-continuation targets such as KV pages. + scatter_rows(proposals, torch.tensor([0, 2]), retained, torch.tensor([True, False]), allow_zero=True) + assert torch.equal(retained[0, :3], proposals[0]) + + +def test_scatter_rows_respects_dynamic_memory_capacity(): + from ignition.components.state import scatter_rows + + retained = torch.full((6, 4), -1.0) + proposals = torch.arange(8, dtype=torch.float32).view(2, 4) + capacity = torch.tensor([3, 0], dtype=torch.int64) + scatter_rows(proposals, torch.tensor([2, 4]), retained, torch.tensor([True, True]), memory_capacity=capacity) + assert torch.equal(retained[2], proposals[0]) + assert retained[4].eq(-1).all() + capacity[0] = 5 + scatter_rows(proposals, torch.tensor([2, 4]), retained, torch.tensor([False, True]), memory_capacity=capacity) + assert torch.equal(retained[4], proposals[1]) + with pytest.raises(ValueError, match="memory_capacity"): + scatter_rows(proposals, torch.tensor([1, 2]), retained, torch.tensor([True, True]), + memory_capacity=torch.tensor([3], dtype=torch.int32)) + + +@pytest.mark.skipif( + not torch.cuda.is_available(), + reason="requires CUDA", +) +def test_cuda_scatter_rows_dynamic_capacity_and_null_slot_protection(): + import os + + if os.environ.get("FLARE_RUN_CUDA_TESTS") != "1": + pytest.skip("requires FLARE_RUN_CUDA_TESTS=1") + from ignition.components.state import gather_rows, scatter_rows + + device = torch.device("cuda") + retained = torch.full((6, 4), -1.0, device=device) + proposals = torch.arange(8, dtype=torch.float32, device=device).view(2, 4) + capacity = torch.tensor([3, 0], dtype=torch.int64, device=device) + + # Null slot 0 is rejected by default; slot 4 is rejected while capacity[0] == 3. + scatter_rows(proposals, torch.tensor([0, 4], dtype=torch.int64, device=device), retained, + torch.tensor([True, True], device=device), memory_capacity=capacity) + assert retained[0].eq(-1).all() and retained[4].eq(-1).all() + + # Raising live capacity permits slot 4 without recompiling. + capacity[0] = 5 + scatter_rows(proposals, torch.tensor([2, 4], dtype=torch.int64, device=device), retained, + torch.tensor([True, True], device=device), memory_capacity=capacity) + assert torch.equal(retained[2], proposals[0]) + assert torch.equal(retained[4], proposals[1]) + + # Explicit allow_zero=True writes slot 0 for 0-indexed page tables. + scatter_rows(proposals, torch.tensor([0, 2], dtype=torch.int64, device=device), retained, + torch.tensor([True, False], device=device), allow_zero=True) + assert torch.equal(retained[0], proposals[0]) + + gathered = torch.empty((2, 4), dtype=torch.float32, device=device) + gather_rows(retained, torch.tensor([4, 2], dtype=torch.int32, device=device), gathered) + assert torch.equal(gathered, proposals[[1, 0]]) diff --git a/tests/preparation/test_frontend_spec.py b/tests/preparation/test_frontend_spec.py new file mode 100644 index 000000000..7e7585a6e --- /dev/null +++ b/tests/preparation/test_frontend_spec.py @@ -0,0 +1,104 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Recipe-owned ImageProcessorSpec contracts and Helios ImageSettings wire validation.""" + +import json +import pytest + +from ignition.preparation.frontend import ( + IMAGE_PROFILES, + ImageProcessorSpec, + PromptEncoder, + image_settings, + prepare_frontend, +) + + +def test_image_processor_spec_validates_fields_and_extracts_payload(): + spec = ImageProcessorSpec( + profile="qwen", + label="", + processor_fields={"processor_class": "ExampleProcessor"}, + image_processor_fields={"patch_size": 16}, + image_processor_optional_fields={"do_resize": True}, + size_fields={"shortest_edge": 65536, "longest_edge": 16777216}, + model_types=("example_v1",), + vision_fields={"patch_size": 16}, + extract=lambda image, model: { + "min_pixels": 65536, + "max_pixels": 16777216, + "position_side": 48, + "image_token_id": model["image_token_id"], + "video_token_id": model["video_token_id"], + }, + ) + processor = { + "processor_class": "ExampleProcessor", + "patch_size": 16, + "size": {"shortest_edge": 65536, "longest_edge": 16777216}, + } + model = { + "model_type": "example_v1", + "image_token_id": 100, + "video_token_id": 101, + "vision_config": {"patch_size": 16}, + } + assert image_settings(processor, model, spec) == { + "qwen": { + "min_pixels": 65536, + "max_pixels": 16777216, + "position_side": 48, + "image_token_id": 100, + "video_token_id": 101, + } + } + with pytest.raises(ValueError, match="model_type"): + image_settings(processor, {**model, "model_type": "other"}, spec) + with pytest.raises(ValueError, match="do_resize"): + image_settings({**processor, "do_resize": False}, model, spec) + with pytest.raises(TypeError, match="ImageProcessorSpec"): + image_settings(processor, model, "qwen") + + +def test_prepare_frontend_uses_spec_default_preprocessor_and_rejects_raw_strings(tmp_path): + (tmp_path / "tokenizer_config.json").write_text(json.dumps({"eos_token": ""})) + (tmp_path / "config.json").write_text(json.dumps({"model_type": "grid_model", "vision_config": {"patch": 20}})) + (tmp_path / "processor_config.json").write_text(json.dumps({ + "processor_class": "GridProcessor", + "image_processor": {"size": {"height": 40, "width": 40}}, + })) + spec = ImageProcessorSpec( + profile="padded_grid", + label="padded-grid", + processor_fields={"processor_class": "GridProcessor"}, + image_processor_key="image_processor", + image_processor_fields={"size": {"height": 40, "width": 40}}, + image_processor_exact_keys=True, + model_types=("grid_model",), + vision_fields={"patch": 20}, + default_preprocessor="processor_config.json", + ) + result = prepare_frontend(tmp_path, eos_token_ids=[7], image_spec=spec) + assert result["image"] == {"padded_grid": {}} + with pytest.raises(TypeError, match="ImageProcessorSpec"): + prepare_frontend(tmp_path, eos_token_ids=[7], image_spec="padded_grid") + with pytest.raises(ValueError, match="differs from the prompt encoder"): + prepare_frontend(tmp_path, eos_token_ids=[7], prompt_encoder=PromptEncoder.DEEPSEEK_V4, image_spec=spec) + + +def test_image_processor_spec_rejects_unknown_profile_and_invalid_mimo_payload(): + with pytest.raises(ValueError, match="unsupported image preprocessing profile"): + ImageProcessorSpec(profile="unknown_profile") + assert {"padded_grid", "glm", "radio", "moonvit", "deepseek_row_major", "deepseek4", "qwen", "mimo"} == IMAGE_PROFILES + bad_mimo = ImageProcessorSpec( + profile="mimo", + extract=lambda image, model: { + "min_pixels": 100, + "max_pixels": 50, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + }, + ) + with pytest.raises(ValueError, match="resize area"): + image_settings({}, {}, bad_mimo)