File size: 14,886 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
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
"""Parallel, memoized prompt-envelope preflight for the safety gate.

``_validate_prompt_envelope`` (in :mod:`backend`) is the safety gate that runs
*before* a trainer can touch a GPU: it decodes every row's images through the
real processor and rejects any row whose prompt/SFT envelope exceeds the frozen
token budget. On the EVI-core-v2 matrix that is ~46k rows decoded serially per
launch — several minutes of GPU-idle time that the lazy image loader does not
reach (it is a separate code path from dataset materialization).

This module keeps the gate *bit-identical* while removing the stall two ways:

1. **Parallelize.** The per-row check is independent, so a **thread** pool
   validates the rows concurrently. The per-row work (image decode, rust
   tokenization, torch image preprocessing) releases the GIL, so threads give
   real parallelism; and threads share the process, so they cannot deadlock on
   the torch/tokenizer locks the model-loaded parent already holds. (A fork
   process pool deadlocked here in practice — fork is unsafe once the VLM
   processor/model is loaded, even with CUDA still on CPU.)
2. **Memoize.** The verdict is keyed by the frozen dataset identity, arm,
   processor revision, limits, and row count.  The release builder establishes
   that identity once; repeat launches do not serialize and hash all 46K
   prepared rows merely to decide whether a cached verdict can be reused.

Correctness guarantees:

* The check body is the exact logic of the original serial loop; the lowest-
  index failure is raised with the identical ``row {index} ...`` message.
* On *any* pool infrastructure failure the gate falls back to the original
  serial scan, so the gate can never be weakened by a threading fault.
* The cache key binds the frozen data identity/path, arm, row count, pinned
  model revision, token limits, SFT flag, and a schema version.  A logic change
  bumps the schema version.  This intentionally trusts the already-built
  release instead of replaying content authentication during training.
"""

from __future__ import annotations

import copy
import os
import warnings
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any

from ..hashing import canonical_json_hash

# Bump when the validation logic in ``_validate_one_row`` changes so a stale
# verdict marker can never mask a logic change.
PREFLIGHT_SCHEMA_VERSION = 3


def _validate_one_row(
    row: Mapping[str, Any],
    processor: Any,
    *,
    sft: bool,
    max_prompt_tokens: int,
    total_context_tokens: int,
) -> None:
    """Validate a single row's prompt/SFT envelope.

    Raises ``BackendContractError`` (detail without a row index) on any
    violation. The row index is attached by the caller so the lowest-index
    failure can be reported, matching the original serial loop's messages.
    """
    from .backend import BackendContractError, _input_length

    raw_paths = row.get("image_paths")
    if not isinstance(raw_paths, list) or not raw_paths:
        raise BackendContractError("has no images for token preflight")
    prompt = copy.deepcopy(list(row["prompt"]))
    path_iterator = iter(str(path) for path in raw_paths)
    for message in prompt:
        content = message.get("content")
        if not isinstance(content, list):
            continue
        for item in content:
            if isinstance(item, dict) and item.get("type") == "image":
                try:
                    item["path"] = next(path_iterator)
                except StopIteration as exc:
                    raise BackendContractError(
                        "has fewer images than placeholders"
                    ) from exc
    try:
        next(path_iterator)
    except StopIteration:
        pass
    else:
        raise BackendContractError("has more images than prompt placeholders")
    prompt_tokens = _input_length(processor, prompt)
    if prompt_tokens > max_prompt_tokens:
        raise BackendContractError(
            f"prompt has {prompt_tokens}>{max_prompt_tokens} tokens"
        )
    if sft:
        full_messages = prompt + list(row["completion"])
        total = _input_length(processor, full_messages)
        if total > total_context_tokens:
            raise BackendContractError(
                f"SFT sequence has {total}>{total_context_tokens} tokens"
            )


def _validate_chunk(
    rows: Sequence[Mapping[str, Any]],
    processor: Any,
    chunk: tuple[int, int, bool, int, int],
) -> list[tuple[int, str]]:
    """Validate rows ``[start, end)``.

    Returns ``(index, detail)`` pairs for every violation in the chunk so the
    caller can raise the lowest-index failure with the serial loop's message.
    ``rows``/``processor`` are passed explicitly (not via module globals) so the
    worker is a pure function of its arguments.
    """
    from .backend import BackendContractError

    start, end, sft, max_prompt_tokens, total_context_tokens = chunk
    errors: list[tuple[int, str]] = []
    for index in range(start, end):
        try:
            _validate_one_row(
                rows[index],
                processor,
                sft=sft,
                max_prompt_tokens=max_prompt_tokens,
                total_context_tokens=total_context_tokens,
            )
        except BackendContractError as exc:
            errors.append((index, str(exc)))
    return errors


def _worker_count() -> int:
    env = os.environ.get("EXPLICIT_PREFLIGHT_WORKERS")
    if env and env.strip():
        try:
            return max(1, int(env))
        except ValueError:
            pass
    return min(os.cpu_count() or 8, 16)


def validate_prompt_envelope_parallel(
    rows: Sequence[Mapping[str, Any]],
    processor: Any,
    *,
    sft: bool,
    max_prompt_tokens: int,
    total_context_tokens: int,
) -> None:
    """Validate every row, raising the lowest-index violation.

    Parallelized with a **thread** pool, not a process pool. The per-row work
    (image decode, rust tokenization, torch image preprocessing) releases the
    GIL, so threads give real parallelism here — and unlike a fork pool they
    share the process, so they cannot deadlock on the torch/tokenizer locks the
    model-loaded parent already holds. (A fork pool deadlocked here in practice;
    fork is unsafe once the VLM processor/model is loaded.) Torch's own thread
    pool is pinned to a single thread so the thread pool below is the only
    parallelism layer. Falls back to the serial scan on any pool fault so the
    gate is never weakened.
    """
    from .backend import BackendContractError

    if not rows:
        return
    workers = _worker_count()
    count = len(rows)
    # ~8 chunks per worker for load balancing; rows are cheap to split.
    chunks_per_worker = 8
    chunk_size = max(1, count // (workers * chunks_per_worker))
    chunks: list[tuple[int, int, bool, int, int]] = []
    for start in range(0, count, chunk_size):
        chunks.append(
            (start, min(start + chunk_size, count), sft, max_prompt_tokens, total_context_tokens)
        )

    prior_intra = os.environ.get("TORCH_NUM_THREADS")
    prior_inter = os.environ.get("TORCH_NUM_INTRAOP_THREADS")
    os.environ["TORCH_NUM_THREADS"] = "1"
    os.environ["TORCH_NUM_INTRAOP_THREADS"] = "1"
    try:
        import torch

        torch.set_num_threads(1)
    except Exception:  # noqa: BLE001 - torch optional at import time
        pass

    try:
        from concurrent.futures import ThreadPoolExecutor

        with ThreadPoolExecutor(max_workers=min(workers, len(chunks))) as pool:
            collected = list(
                pool.map(
                    lambda chunk: _validate_chunk(rows, processor, chunk),
                    chunks,
                )
            )
    except BackendContractError:
        raise
    except Exception as exc:  # noqa: BLE001 - any pool fault falls back to serial
        warnings.warn(
            f"preflight parallel pool failed ({exc!r}); falling back to serial scan",
            stacklevel=2,
        )
        _validate_prompt_envelope_serial(
            rows,
            processor,
            sft=sft,
            max_prompt_tokens=max_prompt_tokens,
            total_context_tokens=total_context_tokens,
        )
        return
    finally:
        if prior_intra is None:
            os.environ.pop("TORCH_NUM_INTRAOP_THREADS", None)
        else:
            os.environ["TORCH_NUM_INTRAOP_THREADS"] = prior_intra
        if prior_inter is None:
            os.environ.pop("TORCH_NUM_THREADS", None)
        else:
            os.environ["TORCH_NUM_THREADS"] = prior_inter

    errors = [pair for batch in collected for pair in batch]
    if errors:
        index, detail = min(errors, key=lambda pair: pair[0])
        raise BackendContractError(f"row {index} {detail}")


def _validate_prompt_envelope_serial(
    rows: Sequence[Mapping[str, Any]],
    processor: Any,
    *,
    sft: bool,
    max_prompt_tokens: int,
    total_context_tokens: int,
) -> None:
    """The original serial scan — the bit-identical source of truth / fallback."""
    from .backend import BackendContractError, _input_length

    for index, row in enumerate(rows):
        raw_paths = row.get("image_paths")
        if not isinstance(raw_paths, list) or not raw_paths:
            raise BackendContractError(f"row {index} has no images for token preflight")
        prompt = copy.deepcopy(list(row["prompt"]))
        path_iterator = iter(str(path) for path in raw_paths)
        for message in prompt:
            content = message.get("content")
            if not isinstance(content, list):
                continue
            for item in content:
                if isinstance(item, dict) and item.get("type") == "image":
                    try:
                        item["path"] = next(path_iterator)
                    except StopIteration as exc:
                        raise BackendContractError(
                            f"row {index} has fewer images than placeholders"
                        ) from exc
        try:
            next(path_iterator)
        except StopIteration:
            pass
        else:
            raise BackendContractError(
                f"row {index} has more images than prompt placeholders"
            )
        prompt_tokens = _input_length(processor, prompt)
        if prompt_tokens > max_prompt_tokens:
            raise BackendContractError(
                f"row {index} prompt has {prompt_tokens}>{max_prompt_tokens} tokens"
            )
        if sft:
            full_messages = prompt + list(row["completion"])
            total = _input_length(processor, full_messages)
            if total > total_context_tokens:
                raise BackendContractError(
                    f"row {index} SFT sequence has {total}>{total_context_tokens} tokens"
                )


def preflight_cache_key(
    runtime: Mapping[str, Any],
    rows: Sequence[Mapping[str, Any]],
    *,
    sft: bool,
    max_prompt_tokens: int,
    total_context_tokens: int,
) -> str:
    """Build a cheap cache key from frozen identities, never row contents."""
    return canonical_json_hash(
        {
            "schema_version": PREFLIGHT_SCHEMA_VERSION,
            "sft": sft,
            "max_prompt_tokens": max_prompt_tokens,
            "total_context_tokens": total_context_tokens,
            "model_revision": runtime.get("model_revision"),
            "model_snapshot_sha256": runtime.get("model_snapshot_sha256"),
            "dataset_path": runtime.get("dataset_path"),
            "dataset_manifest_sha256": (
                runtime.get("_launch_manifest", {}).get("dataset_manifest_sha256")
                if isinstance(runtime.get("_launch_manifest"), Mapping)
                else None
            ),
            "comparison_slot_manifest_sha256": runtime.get(
                "comparison_slot_manifest_sha256"
            ),
            "arm": runtime.get("arm"),
            "record_count": len(rows),
        }
    )


def _preflight_cache_dir() -> Path | None:
    explicit = os.environ.get("EXPLICIT_PREFLIGHT_CACHE_DIR", "").strip()
    if explicit:
        return Path(explicit)
    cache_root = os.environ.get("EXPLICIT_CACHE_ROOT", "").strip()
    if cache_root:
        return Path(cache_root) / "preflight-verdicts"
    return None


def _read_marker(path: Path, expected_key: str, record_count: int) -> bool:
    """True iff ``path`` holds a valid verdict marker for this key/count."""
    if not path.is_file():
        return False
    try:
        import json

        with path.open("r", encoding="utf-8") as handle:
            marker = json.load(handle)
    except (OSError, ValueError):
        return False
    return (
        isinstance(marker, Mapping)
        and marker.get("schema_version") == PREFLIGHT_SCHEMA_VERSION
        and marker.get("key") == expected_key
        and marker.get("record_count") == record_count
    )


def run_preflight(
    runtime: Mapping[str, Any],
    rows: Sequence[Mapping[str, Any]],
    processor: Any,
    *,
    sft: bool,
    max_prompt_tokens: int,
    total_context_tokens: int,
) -> bool:
    """Run the prompt-envelope gate with verdict memoization.

    Returns ``True`` on a cache hit (validation skipped), ``False`` when the
    full validation was run (cache miss). Always raises ``BackendContractError``
    on any violating row, hit or miss.
    """
    key = preflight_cache_key(
        runtime,
        rows,
        sft=sft,
        max_prompt_tokens=max_prompt_tokens,
        total_context_tokens=total_context_tokens,
    )
    record_count = len(rows)
    cache_dir = _preflight_cache_dir()
    marker_path = cache_dir / f"preflight-{key}.json" if cache_dir is not None else None

    if marker_path is not None and _read_marker(marker_path, key, record_count):
        return True

    validate_prompt_envelope_parallel(
        rows,
        processor,
        sft=sft,
        max_prompt_tokens=max_prompt_tokens,
        total_context_tokens=total_context_tokens,
    )

    if marker_path is not None:
        from ..atomic_io import atomic_write_json

        marker_path.parent.mkdir(parents=True, exist_ok=True)
        atomic_write_json(
            marker_path,
            {
                "schema_version": PREFLIGHT_SCHEMA_VERSION,
                "key": key,
                "record_count": record_count,
                "sft": sft,
                "max_prompt_tokens": max_prompt_tokens,
                "total_context_tokens": total_context_tokens,
                "model_revision": runtime.get("model_revision"),
                "model_snapshot_sha256": runtime.get("model_snapshot_sha256"),
                "comparison_slot_manifest_sha256": runtime.get(
                    "comparison_slot_manifest_sha256"
                ),
            },
        )
    return False