Files
rea/src/model/PytorchArtifactReader.ts
T

724 lines
23 KiB
TypeScript

import { createHash, type Hash } from "node:crypto";
import type { FileHandle } from "node:fs/promises";
import { setImmediate } from "node:timers/promises";
import type { Readable } from "node:stream";
import type {
ModelTensor,
PickleFacts,
PytorchFacts,
} from "../domain/model/modelArtifact.js";
import {
malformedInput,
truncatedInput,
unsupportedInput,
} from "../domain/parseFailure.js";
import { BinaryReader } from "../domain/binaryContainer.js";
import { decodeStrictUtf8 } from "../domain/strictUtf8.js";
import { sha256Hex } from "../kernel/sha256Hex.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
import {
ArtifactReaderFailure,
assertArtifactReadActive,
throwZipPackageFailure,
ZipArtifactReader,
type ArtifactEntry,
} from "../resources/index.js";
import {
MODEL_FORMAT,
MODEL_HEADER_BYTES,
MODEL_REPORT_BYTES,
modelCapacityFailure,
ModelReportBudget,
rejectForeignZip,
rejectModel,
} from "./ModelFormat.js";
import {
operationZipMemberCount,
zipMemberCountConstraint,
} from "../config/artifactMemberCount.js";
import {
pickleFacts,
placeTensors,
storageReference,
storageRows,
STORAGE_ITEMSIZE,
tensorRows,
type StorageRecord,
type StorageReference,
type WalkedStream,
} from "./PickleInspection.js";
import {
PickleWalker,
exactInt,
PickleWork,
type PickleBudgets,
type PickleNode,
} from "./PickleWalker.js";
/** Facts and read accounting for a PyTorch checkpoint or standalone pickle. */
export interface PickleArtifact {
readonly format: "pytorch-zip" | "pytorch-legacy" | "pickle";
readonly version: number | null;
readonly byte_order: "little" | "big" | null;
readonly alignment: number | null;
readonly tensor_data_offset: number | null;
readonly metadata: [];
readonly tensors: ModelTensor[];
/** False when a tensor rebuild call could not be read, so rows omit tensors. */
readonly tensors_complete: boolean;
readonly limitations: string[];
readonly pickle: PickleFacts;
readonly pytorch?: PytorchFacts;
readonly header_length: number;
readonly header_sha256: string;
readonly sha256: string | null;
readonly bytes_read: number;
}
/** torch.save's legacy (non-ZIP) format begins with this pickled integer. */
const LEGACY_MAGIC = 0x1950a86a20f9469cfc6cn;
const LEGACY_PROTOCOL = 1001n;
const FEED_SLICE = 4 * 1024 * 1024;
const RECORD_TEXT_BYTES = 4096;
const MODEL_OPERATION = "inspect_model_artifact";
/** Feed one complete or growing stream in bounded slices so cancellation is observed. */
const feedSlices = async (
walker: PickleWalker,
bytes: Buffer,
final: boolean,
signal: AbortSignal | undefined,
): Promise<boolean> => {
// The slice grows monotonically so one operand larger than a slice still completes.
let end = walker.position;
for (;;) {
assertArtifactReadActive(signal);
end = Math.min(bytes.length, Math.max(end, walker.position) + FEED_SLICE);
const last = end === bytes.length;
if (walker.feed(bytes.subarray(0, end), final && last)) return true;
if (last) return false;
await setImmediate();
}
};
/** A contiguous, hashed-on-demand file prefix bounded by the model header allowance. */
class FilePrefix {
buffer = Buffer.alloc(0);
/** Bytes read outside the contiguous prefix, such as legacy storage counts. */
extraBytes = 0;
constructor(
readonly file: FileHandle,
readonly size: number,
readonly signal: AbortSignal | undefined,
) {}
get loaded(): number {
return this.buffer.length;
}
get complete(): boolean {
return this.loaded >= this.size;
}
async grow(): Promise<void> {
const ceiling = Math.min(this.size, MODEL_HEADER_BYTES);
if (this.loaded >= ceiling)
throw modelCapacityFailure(
"header-bytes",
"Pickle streams exceed 100,000,000 bytes before their last STOP. This release has no runtime override.",
);
const target = Math.min(
ceiling,
Math.max(this.loaded + 65536, this.loaded * 2),
);
const next = Buffer.allocUnsafe(target);
this.buffer.copy(next);
await readExactly(this.file, next, this.loaded, target, this.signal);
this.buffer = next;
}
async readAt(position: number, length: number): Promise<Buffer> {
if (position + length <= this.loaded)
return this.buffer.subarray(position, position + length);
const bytes = Buffer.allocUnsafe(length);
await readExactly(this.file, bytes, 0, length, this.signal, position);
this.extraBytes += length;
return bytes;
}
}
const readExactly = async (
file: FileHandle,
target: Buffer,
from: number,
to: number,
signal: AbortSignal | undefined,
position = from,
): Promise<void> => {
let offset = from;
while (offset < to) {
assertArtifactReadActive(signal);
const { bytesRead } = await file.read(
target,
offset,
to - offset,
position + offset - from,
);
if (bytesRead === 0)
throw new ArtifactReaderFailure(
"integrity",
"Model ended before its admitted file extent",
{ integrityCheck: "read-coverage" },
);
offset += bytesRead;
}
};
/** Stream the file from `from` into `hash`; bytes before it were hashed by the caller. */
const hashRemainder = async (
file: FileHandle,
size: number,
from: number,
hash: Hash,
signal: AbortSignal | undefined,
): Promise<void> => {
const buffer = Buffer.allocUnsafe(1024 * 1024);
for (let position = from; position < size;) {
const length = Math.min(buffer.length, size - position);
await readExactly(file, buffer, 0, length, signal, position);
hash.update(buffer.subarray(0, length));
position += length;
}
};
/** Storage references in first-appearance order; later conflicting declarations keep the first. */
const storageReferences = (
walker: PickleWalker,
): Map<string, StorageReference> => {
const byKey = new Map<string, StorageReference>();
for (const node of walker.persistent) {
const reference = storageReference(node);
if (reference !== undefined && !byKey.has(reference.key))
byKey.set(reference.key, reference);
}
return byKey;
};
/** Shared tensor and storage interpretation of a walked data stream. */
const interpret = (
data: PickleWalker,
record: (key: string) => StorageRecord | undefined,
budget: ModelReportBudget,
references: ReadonlyMap<string, StorageReference> = storageReferences(data),
) => {
// Every storage persistent ID is inventoried and checked, whether or not a tensor uses it.
const storages = storageRows([...references.values()], record, budget);
const { tensors: placed, uninterpretable } = placeTensors(
data.result!,
budget,
);
const { rows, unnamed } = tensorRows(placed, storages, budget);
const limitations: string[] = [];
if (unnamed > 0)
limitations.push(
`${String(unnamed)} tensor(s) are not reached through one unshared chain of string or integer container keys from the pickled root; their names are #<index> and json_pointer is null.`,
);
if (uninterpretable > 0)
limitations.push(
`${String(uninterpretable)} tensor rebuild call(s) have arguments that do not state a storage, offset, shape and stride; they remain in pickle.references without tensor rows.`,
);
return {
rows,
storages: [...storages.values()],
limitations,
complete: uninterpretable === 0,
};
};
/** Facts a reader has completed, offered before full-file hashing can fail or be cancelled. */
export type RetainPickleFacts = (facts: PickleArtifact) => void;
/** Standalone pickle or legacy torch.save file, read as a sequential prefix. */
export const readPickleFile = async (
file: FileHandle,
size: number,
full: boolean,
budgets: PickleBudgets,
signal: AbortSignal | undefined,
retain: RetainPickleFacts,
): Promise<PickleArtifact> => {
const budget = new ModelReportBudget();
const prefix = new FilePrefix(file, size, signal);
const work = new PickleWork(budgets);
const streams: WalkedStream[] = [];
const walk = async (start: number, role: WalkedStream["role"]) => {
const walker = new PickleWalker({ fileOffset: start, member: null }, work);
for (;;) {
if (
prefix.loaded > start &&
(await feedSlices(
walker,
prefix.buffer.subarray(start),
prefix.complete,
signal,
))
)
break;
if (prefix.complete)
// An empty remainder: the stream has no opcode at all.
walker.feed(Buffer.alloc(0), true);
await prefix.grow();
}
streams.push({ walker, role, length: walker.position });
return walker;
};
const first = await walk(0, "data");
const legacy = exactInt(first.result) === LEGACY_MAGIC;
const limitations: string[] = [];
let headerEnd = first.position;
let version: number | null = null;
let byteOrder: "little" | "big" | null = null;
let tensorDataOffset: number | null = null;
let data = first;
let references: ReadonlyMap<string, StorageReference> | undefined;
const records = new Map<string, StorageRecord>();
if (legacy) {
streams[0] = { ...streams[0]!, role: "magic" };
const protocol = await walk(headerEnd, "protocol");
const declared = exactInt(protocol.result);
if (declared !== LEGACY_PROTOCOL)
throw malformedInput(
MODEL_FORMAT,
`Legacy torch.save protocol version ${declared?.toString() ?? "is not an integer"}; expected 1001`,
{ offset: headerEnd },
);
version = Number(LEGACY_PROTOCOL);
const sysInfo = await walk(
protocol.site.fileOffset! + protocol.position,
"sys-info",
);
byteOrder = legacyByteOrder(sysInfo.result!);
data = await walk(sysInfo.site.fileOffset! + sysInfo.position, "data");
const keysStart = data.site.fileOffset! + data.position;
const keys = await walk(keysStart, "storage-keys");
headerEnd = keys.site.fileOffset! + keys.position;
tensorDataOffset = headerEnd;
const keyList = keys.result!;
if (
keyList.kind !== "list" ||
!keyList.items.every((item) => item.kind === "str")
)
throw malformedInput(
MODEL_FORMAT,
"Legacy torch.save storage key list is not a list of strings",
{ offset: keysStart },
);
references = storageReferences(data);
const declaredKeys = new Set(
keyList.items.map((item) => (item.kind === "str" ? item.value : "")),
);
for (const key of references.keys())
if (!declaredKeys.has(key))
throw malformedInput(
MODEL_FORMAT,
`Legacy torch.save storage ${key} is referenced by the data pickle but has no entry in the storage key list`,
{ offset: keysStart },
);
let position = headerEnd;
for (const [index, item] of keyList.items.entries()) {
const key = item.kind === "str" ? item.value : "";
const reference = references.get(key);
if (reference === undefined)
throw malformedInput(
MODEL_FORMAT,
`Legacy torch.save storage key ${key} has no persistent storage declaration`,
{ offset: keysStart },
);
const itemsize = STORAGE_ITEMSIZE(reference.storageType);
if (itemsize === null) {
limitations.push(
`Legacy storage ${key} has unknown element size; file offsets of it and ${String(keyList.items.length - index - 1)} later storage(s) are unknown.`,
);
break;
}
if (position + 8 > size)
throw truncatedInput(
MODEL_FORMAT,
`Legacy storage ${key} element count at file offset ${String(position)} is truncated`,
{ offset: position },
);
const countBytes = await prefix.readAt(position, 8);
const elements = new BinaryReader(
countBytes,
byteOrder !== "big",
MODEL_FORMAT,
).word(0, 64);
if (
reference.elementCount !== null &&
elements !== reference.elementCount
)
throw malformedInput(
MODEL_FORMAT,
`Legacy storage ${key} declares ${elements.toString()} elements at file offset ${String(position)}; its persistent ID declares ${reference.elementCount.toString()}`,
{ offset: position },
);
const bytes = elements * BigInt(itemsize);
const end = BigInt(position) + 8n + bytes;
if (end > BigInt(size))
throw truncatedInput(
MODEL_FORMAT,
`Legacy storage ${key} at file offset ${String(position)} extends past the end of the file`,
{ offset: position },
);
records.set(key, {
record: null,
recordBytes: Number(bytes),
fileOffset: position + 8,
declaredElements: elements,
});
position = Number(end);
if (index === keyList.items.length - 1 && position < size)
limitations.push(
`${String(size - position)} byte(s) follow the last legacy storage and were not interpreted.`,
);
}
if (byteOrder === null)
limitations.push(
"The legacy sys_info record does not state little_endian; storage byte order is unknown.",
);
} else {
if (headerEnd < size)
limitations.push(
`${String(size - headerEnd)} byte(s) follow the pickle's STOP; an unpickler reads only the first stream and REA did not interpret them.`,
);
limitations.push(
"A standalone pickle carries no storage bytes; storage sizes and tensor file offsets are unknown.",
);
}
const interpreted = interpret(
data,
(key) => records.get(key),
budget,
references,
);
const facts = pickleFacts(streams, budget);
const artifact: PickleArtifact = {
format: legacy ? "pytorch-legacy" : "pickle",
version,
byte_order: byteOrder,
alignment: null,
tensor_data_offset: tensorDataOffset,
metadata: [],
tensors: interpreted.rows,
tensors_complete: interpreted.complete,
limitations: [
...facts.limitations,
...limitations,
...interpreted.limitations,
],
pickle: facts.facts,
...(legacy
? {
pytorch: {
layout: "legacy" as const,
archive_prefix: null,
records: [],
storages: interpreted.storages,
},
}
: {}),
header_length: headerEnd,
header_sha256: sha256Hex(prefix.buffer.subarray(0, headerEnd)),
sha256: null,
bytes_read: prefix.loaded + prefix.extraBytes,
};
if (!full) return artifact;
retain(artifact);
const hash = createHash("sha256").update(prefix.buffer);
await hashRemainder(file, size, prefix.loaded, hash, signal);
return { ...artifact, sha256: hash.digest("hex"), bytes_read: size };
};
const legacyByteOrder = (node: PickleNode): "little" | "big" | null => {
if (node.kind !== "dict") return null;
for (const [key, value] of node.entries)
if (key.kind === "str" && key.value === "little_endian")
return value.kind === "bool" ? (value.value ? "little" : "big") : null;
return null;
};
type RecordRole = PytorchFacts["records"][number]["role"];
const recordRole = (relative: string): RecordRole => {
switch (relative) {
case "data.pkl":
return "data-pickle";
case "version":
case ".data/version":
return "version";
case "byteorder":
return "byteorder";
case ".data/serialization_id":
return "serialization-id";
case ".format_version":
return "format-version";
case ".storage_alignment":
return "storage-alignment";
default:
return /^data\/[^/]+$/u.test(relative) ? "storage" : "other";
}
};
const readMember = async (
reader: ZipArtifactReader,
entry: ArtifactEntry,
maximum: number,
signal: AbortSignal | undefined,
): Promise<Buffer> => {
if (entry.encrypted)
rejectModel(`PyTorch archive record ${entry.path} is encrypted`);
const stream: Readable = await reader.open(entry, signal);
const chunks: Buffer[] = [];
let length = 0;
for await (const chunk of stream as AsyncIterable<Buffer>) {
length += chunk.length;
if (length > maximum) {
stream.destroy();
throw modelCapacityFailure(
"header-bytes",
`PyTorch archive record ${entry.path} exceeds ${String(maximum)} bytes. This release has no runtime override.`,
);
}
chunks.push(chunk);
}
return Buffer.concat(chunks, length);
};
/** PyTorch's ZIP checkpoint layout: `<prefix>/data.pkl` plus `<prefix>/data/<key>` records. */
export const readPytorchZip = async (
path: string,
source: StableRegularFileDescriptor,
size: number,
full: boolean,
budgets: PickleBudgets,
signal: AbortSignal | undefined,
retain: RetainPickleFacts,
): Promise<PickleArtifact> => {
const memberCount = operationZipMemberCount(process.env);
// No directory read may exceed what a report could retain.
const reader = new ZipArtifactReader(
path,
"zip",
MODEL_REPORT_BYTES,
source,
undefined,
memberCount.value,
);
try {
return await readPytorchArchive(
reader,
source,
size,
full,
budgets,
signal,
retain,
);
} catch (cause) {
const count =
cause instanceof ArtifactReaderFailure
? zipMemberCountConstraint(MODEL_OPERATION, cause, memberCount)
: undefined;
if (count !== undefined) throw count;
// An encrypted or otherwise unsupported archive feature is outside this reader's coverage.
if (
cause instanceof ArtifactReaderFailure &&
cause.reason === "unavailable"
)
throw unsupportedInput(
MODEL_FORMAT,
`PyTorch checkpoint ZIP uses an unsupported layout: ${cause.message}`,
{ cause },
);
return throwZipPackageFailure(cause, MODEL_FORMAT, "PyTorch checkpoint");
} finally {
await reader.close();
}
};
const readPytorchArchive = async (
reader: ZipArtifactReader,
source: StableRegularFileDescriptor,
size: number,
full: boolean,
budgets: PickleBudgets,
signal: AbortSignal | undefined,
retain: RetainPickleFacts,
): Promise<PickleArtifact> => {
const budget = new ModelReportBudget();
const files: ArtifactEntry[] = [];
const dataEntries: ArtifactEntry[] = [];
// Each listed name may become a record row; charge it as it is enumerated.
for await (const entry of reader.entries(signal))
if (entry.kind === "file") {
budget.charge(128 + 2 * entry.path.length);
files.push(entry);
if (/^[^/]+\/data\.pkl$/u.test(entry.path)) dataEntries.push(entry);
}
const [dataEntry] = dataEntries;
if (dataEntry === undefined)
return rejectForeignZip(
"ZIP archive has no <name>/data.pkl record, so it is not a PyTorch checkpoint",
);
if (dataEntries.length > 1)
rejectForeignZip(
`ZIP archive has ${String(dataEntries.length)} <name>/data.pkl records, so its PyTorch archive name is ambiguous`,
);
const prefix = dataEntry.path.slice(0, dataEntry.path.indexOf("/"));
const limitations: string[] = [];
const records: PytorchFacts["records"] = [];
const addRecord = (
entry: ArtifactEntry,
role: RecordRole,
value: string | null,
) =>
records.push({ name: entry.path, role, bytes: entry.declaredSize, value });
const storageEntries = new Map<string, ArtifactEntry>();
const values = new Map<RecordRole, string | null>();
let bytesRead = 0;
for (const entry of files) {
const relative = entry.path.startsWith(`${prefix}/`)
? entry.path.slice(prefix.length + 1)
: undefined;
const role = relative === undefined ? "other" : recordRole(relative);
if (role === "storage") {
storageEntries.set(relative!.slice("data/".length), entry);
continue;
}
let value: string | null = null;
if (role !== "data-pickle" && role !== "other") {
if ((entry.declaredSize ?? Infinity) <= RECORD_TEXT_BYTES) {
const bytes = await readMember(
reader,
entry,
RECORD_TEXT_BYTES,
signal,
);
bytesRead += entry.compressedSize ?? bytes.length;
try {
value = decodeStrictUtf8(bytes, "preserve").trim();
} catch {
rejectModel(`PyTorch archive record ${entry.path} is not UTF-8 text`);
}
} else
limitations.push(
`PyTorch archive record ${entry.path} exceeds ${String(RECORD_TEXT_BYTES)} bytes; its value was not read.`,
);
values.set(role, value);
}
// The row and its name were charged at enumeration.
budget.charge(2 * (value?.length ?? 0));
addRecord(entry, role, value);
}
const pickleBytes = await readMember(
reader,
dataEntry,
MODEL_HEADER_BYTES,
signal,
);
bytesRead += dataEntry.compressedSize ?? pickleBytes.length;
const work = new PickleWork(budgets);
const data = new PickleWalker(
{ fileOffset: null, member: dataEntry.path },
work,
);
await feedSlices(data, pickleBytes, true, signal);
const byteorder = values.get("byteorder");
if (
byteorder !== undefined &&
byteorder !== null &&
byteorder !== "little" &&
byteorder !== "big"
)
rejectModel(
`PyTorch byteorder record states ${JSON.stringify(byteorder)}; expected little or big`,
);
if (byteorder === undefined)
limitations.push(
"The archive has no byteorder record. PyTorch's loader then assumes little-endian storage; REA reports the byte order as unknown.",
);
const decimal = (role: RecordRole): number | null => {
const value = values.get(role);
return value != null && /^[0-9]{1,15}$/u.test(value) ? Number(value) : null;
};
const referenced = new Set<string>();
const interpreted = interpret(
data,
(key) => {
referenced.add(key);
const entry = storageEntries.get(key);
if (entry === undefined)
rejectModel(
`PyTorch storage ${key} has no ${prefix}/data/${key} record in the archive`,
{ field: `${prefix}/data/${key}` },
);
return {
record: entry.path,
recordBytes: entry.declaredSize,
fileOffset: null,
declaredElements: null,
};
},
budget,
);
for (const [key, entry] of storageEntries)
if (!referenced.has(key)) addRecord(entry, "storage", null);
if (records.some((record) => record.role === "other"))
limitations.push(
"Archive records with role other were listed but not interpreted.",
);
limitations.push(
"Storage bytes are ZIP records, so tensor file_offset is null; data_offset is relative to the storage record and source_offset is relative to data.pkl.",
);
const facts = pickleFacts(
[{ walker: data, role: "data", length: data.position }],
budget,
);
if (data.position < pickleBytes.length)
limitations.push(
`${String(pickleBytes.length - data.position)} byte(s) follow STOP in ${dataEntry.path} and were not interpreted.`,
);
const artifact: PickleArtifact = {
format: "pytorch-zip",
version: decimal("version"),
byte_order: (byteorder ?? null) as "little" | "big" | null,
alignment: decimal("storage-alignment"),
tensor_data_offset: null,
metadata: [],
tensors: interpreted.rows,
tensors_complete: interpreted.complete,
limitations: [
...facts.limitations,
...limitations,
...interpreted.limitations,
],
pickle: facts.facts,
pytorch: {
layout: "zip",
archive_prefix: prefix,
records,
storages: interpreted.storages,
},
header_length: pickleBytes.length,
header_sha256: sha256Hex(pickleBytes),
sha256: null,
bytes_read: bytesRead,
};
if (!full) return artifact;
retain(artifact);
const hash = createHash("sha256");
await hashRemainder(source.handle, size, 0, hash, signal);
return { ...artifact, sha256: hash.digest("hex"), bytes_read: size };
};