eval-toolkit 0.27.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://eval-toolkit/schemas/manifest.v2.json",
4
+ "version": "2",
5
+ "title": "eval-toolkit RunManifest (v2)",
6
+ "description": "Schema for run_dir/manifest.json. Produced by eval_toolkit.manifest.write_manifest. NeurIPS Reproducibility Checklist-aligned. v2 adds: captured_at (auto-populated ISO-8601 UTC); top-level data_revisions and metadata (replacing meta:/hf_*: prefixed extra_code_versions); tightened gpu_info typing (count: integer, memory_gb: number).",
7
+ "type": "object",
8
+ "required": ["schema_version", "run_id", "captured_at", "code_versions", "env"],
9
+ "properties": {
10
+ "schema_version": {
11
+ "const": "v2"
12
+ },
13
+ "run_id": {
14
+ "type": "string",
15
+ "minLength": 1
16
+ },
17
+ "captured_at": {
18
+ "type": "string",
19
+ "description": "ISO-8601 UTC timestamp captured at build_manifest() call time. Replaces meta:run_timestamp_utc abuse of extra_code_versions in v1 consumers.",
20
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$"
21
+ },
22
+ "git_sha": {
23
+ "type": ["string", "null"]
24
+ },
25
+ "dirty_flag": {
26
+ "type": "boolean",
27
+ "description": "True iff the working tree had uncommitted changes at run time (NeurIPS clean-replay concern)."
28
+ },
29
+ "code_versions": {
30
+ "type": "object",
31
+ "description": "{package_name: version_string} — at minimum eval_toolkit. Caller-declared key dependencies (e.g. transformers, torch, sklearn). For dataset / model revisions use data_revisions; for run-time metadata use metadata.",
32
+ "additionalProperties": {
33
+ "type": "string"
34
+ }
35
+ },
36
+ "data_revisions": {
37
+ "type": "object",
38
+ "description": "{logical_name: revision_string} for input dataset and model revisions. v2 addition (was crammed under extra_code_versions in v1). Recommended key prefixes: 'hf_dataset:<name>' and 'hf_model:<name>'.",
39
+ "additionalProperties": {
40
+ "type": "string"
41
+ }
42
+ },
43
+ "metadata": {
44
+ "type": "object",
45
+ "description": "{label_name: label_value} for caller-supplied run-time labels (cli_args, environment selectors, etc.). v2 addition (was crammed under extra_code_versions in v1).",
46
+ "additionalProperties": {
47
+ "type": "string"
48
+ }
49
+ },
50
+ "seeds": {
51
+ "type": "object",
52
+ "description": "{source: seed} for global / bootstrap / torch / dataloader RNGs.",
53
+ "additionalProperties": {
54
+ "type": "integer"
55
+ }
56
+ },
57
+ "data_hashes": {
58
+ "type": "object",
59
+ "description": "{logical_name: 'sha256:...'} for input artifacts.",
60
+ "additionalProperties": {
61
+ "type": "string"
62
+ }
63
+ },
64
+ "config_hash": {
65
+ "type": "string",
66
+ "description": "SHA-256 over the canonical-JSON encoding of the eval config."
67
+ },
68
+ "env": {
69
+ "type": "object",
70
+ "description": "Environment fingerprint (python, platform, key dep versions).",
71
+ "additionalProperties": {
72
+ "type": "string"
73
+ }
74
+ },
75
+ "gpu_info": {
76
+ "type": "object",
77
+ "description": "{name, count, memory_gb} from nvidia-smi (empty dict if unavailable). v2 tightens count to integer and memory_gb to number.",
78
+ "properties": {
79
+ "name": {"type": "string"},
80
+ "count": {"type": "integer", "minimum": 0},
81
+ "memory_gb": {"type": "number", "minimum": 0}
82
+ },
83
+ "additionalProperties": true
84
+ },
85
+ "cuda_version": {
86
+ "type": ["string", "null"]
87
+ },
88
+ "wall_clock_seconds": {
89
+ "type": ["number", "null"]
90
+ },
91
+ "versioned_objects": {
92
+ "type": "object",
93
+ "description": "{name: version} for any Tier-2 implementation exposing a `version` attribute.",
94
+ "additionalProperties": {
95
+ "type": "string"
96
+ }
97
+ },
98
+ "leakage_report": {
99
+ "type": ["object", "null"],
100
+ "description": "Serialized LeakageReport (or null if no leakage checks ran).",
101
+ "properties": {
102
+ "findings": {
103
+ "type": "array",
104
+ "items": {
105
+ "type": "object",
106
+ "required": ["check_name", "severity", "drop_indices", "evidence", "message", "n_affected"],
107
+ "properties": {
108
+ "check_name": {"type": "string"},
109
+ "severity": {"enum": ["error", "warning", "info"]},
110
+ "drop_indices": {"type": ["object", "null"]},
111
+ "evidence": {"type": "object"},
112
+ "message": {"type": "string"},
113
+ "n_affected": {"type": "integer", "minimum": 0}
114
+ }
115
+ }
116
+ }
117
+ }
118
+ },
119
+ "source_roles": {
120
+ "type": "array",
121
+ "description": "Optional generic source-role metadata for data-quality and evidence audits. Recommended roles: train, calibration, locked_eval, external_diagnostic, excluded; custom roles are allowed.",
122
+ "items": {
123
+ "type": "object",
124
+ "required": ["source", "role"],
125
+ "properties": {
126
+ "source": {"type": "string", "minLength": 1},
127
+ "role": {"type": "string", "minLength": 1},
128
+ "n_rows": {"type": "integer", "minimum": 0},
129
+ "notes": {"type": "string"},
130
+ "metadata": {"type": "object"}
131
+ },
132
+ "additionalProperties": true
133
+ }
134
+ },
135
+ "guardrails": {
136
+ "type": "array",
137
+ "description": "Optional predeclared guardrails for claim/evidence discipline.",
138
+ "items": {"type": "string", "minLength": 1}
139
+ },
140
+ "prediction_artifacts": {
141
+ "type": "array",
142
+ "description": "Optional references to retained prediction artifacts.",
143
+ "items": {
144
+ "type": "object",
145
+ "required": ["uri", "media_type", "columns"],
146
+ "properties": {
147
+ "uri": {"type": "string", "minLength": 1},
148
+ "media_type": {"type": "string", "minLength": 1},
149
+ "sha256": {"type": "string"},
150
+ "n_rows": {"type": "integer", "minimum": 0},
151
+ "role": {
152
+ "oneOf": [
153
+ {"type": "string", "minLength": 1},
154
+ {
155
+ "type": "array",
156
+ "minItems": 1,
157
+ "items": {"type": "string", "minLength": 1}
158
+ }
159
+ ]
160
+ },
161
+ "metadata": {"type": "object"},
162
+ "columns": {
163
+ "type": "object",
164
+ "required": ["label", "score"],
165
+ "properties": {
166
+ "row_id": {"type": "string", "minLength": 1},
167
+ "content_hash": {"type": "string", "minLength": 1},
168
+ "label": {"type": "string", "minLength": 1},
169
+ "score": {"type": "string", "minLength": 1},
170
+ "scorer": {"type": "string", "minLength": 1},
171
+ "slice": {"type": "string", "minLength": 1},
172
+ "text": {"type": "string", "minLength": 1},
173
+ "provenance": {
174
+ "type": "object",
175
+ "additionalProperties": {"type": "string"}
176
+ }
177
+ },
178
+ "additionalProperties": true
179
+ }
180
+ },
181
+ "additionalProperties": true
182
+ }
183
+ }
184
+ },
185
+ "additionalProperties": true
186
+ }
@@ -0,0 +1,186 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://eval-toolkit/schemas/manifest.v3.json",
4
+ "version": "3",
5
+ "title": "eval-toolkit RunManifest (v3)",
6
+ "description": "Schema for run_dir/manifest.json. Produced by eval_toolkit.manifest.write_manifest. NeurIPS Reproducibility Checklist-aligned. v3 adds: contamination_flags (required object; per-scorer contamination posture audit trail). v2 fields preserved. Default schema for new manifests starting v0.23.0.",
7
+ "type": "object",
8
+ "required": ["schema_version", "run_id", "captured_at", "code_versions", "env", "contamination_flags"],
9
+ "properties": {
10
+ "schema_version": {
11
+ "const": "v3"
12
+ },
13
+ "run_id": {
14
+ "type": "string",
15
+ "minLength": 1
16
+ },
17
+ "captured_at": {
18
+ "type": "string",
19
+ "description": "ISO-8601 UTC timestamp captured at build_manifest() call time.",
20
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$"
21
+ },
22
+ "git_sha": {
23
+ "type": ["string", "null"]
24
+ },
25
+ "dirty_flag": {
26
+ "type": "boolean"
27
+ },
28
+ "code_versions": {
29
+ "type": "object",
30
+ "additionalProperties": {
31
+ "type": "string"
32
+ }
33
+ },
34
+ "data_revisions": {
35
+ "type": "object",
36
+ "additionalProperties": {
37
+ "type": "string"
38
+ }
39
+ },
40
+ "metadata": {
41
+ "type": "object",
42
+ "additionalProperties": {
43
+ "type": "string"
44
+ }
45
+ },
46
+ "seeds": {
47
+ "type": "object",
48
+ "additionalProperties": {
49
+ "type": "integer"
50
+ }
51
+ },
52
+ "data_hashes": {
53
+ "type": "object",
54
+ "additionalProperties": {
55
+ "type": "string"
56
+ }
57
+ },
58
+ "config_hash": {
59
+ "type": "string"
60
+ },
61
+ "env": {
62
+ "type": "object",
63
+ "additionalProperties": {
64
+ "type": "string"
65
+ }
66
+ },
67
+ "gpu_info": {
68
+ "type": "object",
69
+ "properties": {
70
+ "name": {"type": "string"},
71
+ "count": {"type": "integer", "minimum": 0},
72
+ "memory_gb": {"type": "number", "minimum": 0}
73
+ },
74
+ "additionalProperties": true
75
+ },
76
+ "cuda_version": {
77
+ "type": ["string", "null"]
78
+ },
79
+ "wall_clock_seconds": {
80
+ "type": ["number", "null"]
81
+ },
82
+ "versioned_objects": {
83
+ "type": "object",
84
+ "additionalProperties": {
85
+ "type": "string"
86
+ }
87
+ },
88
+ "leakage_report": {
89
+ "type": ["object", "null"],
90
+ "properties": {
91
+ "findings": {
92
+ "type": "array",
93
+ "items": {
94
+ "type": "object",
95
+ "required": ["check_name", "severity", "drop_indices", "evidence", "message", "n_affected"],
96
+ "properties": {
97
+ "check_name": {"type": "string"},
98
+ "severity": {"enum": ["error", "warning", "info"]},
99
+ "drop_indices": {"type": ["object", "null"]},
100
+ "evidence": {"type": "object"},
101
+ "message": {"type": "string"},
102
+ "n_affected": {"type": "integer", "minimum": 0}
103
+ }
104
+ }
105
+ }
106
+ }
107
+ },
108
+ "source_roles": {
109
+ "type": "array",
110
+ "items": {
111
+ "type": "object",
112
+ "required": ["source", "role"],
113
+ "properties": {
114
+ "source": {"type": "string", "minLength": 1},
115
+ "role": {"type": "string", "minLength": 1},
116
+ "n_rows": {"type": "integer", "minimum": 0},
117
+ "notes": {"type": "string"},
118
+ "metadata": {"type": "object"}
119
+ },
120
+ "additionalProperties": true
121
+ }
122
+ },
123
+ "guardrails": {
124
+ "type": "array",
125
+ "description": "Optional predeclared guardrails for claim/evidence discipline. v3 may use either string entries (v2 back-compat) or structured objects (e.g., source_freshness_check sub-objects with timestamp + method).",
126
+ "items": {
127
+ "oneOf": [
128
+ {"type": "string", "minLength": 1},
129
+ {"type": "object", "minProperties": 1}
130
+ ]
131
+ }
132
+ },
133
+ "contamination_flags": {
134
+ "type": "object",
135
+ "description": "v3 addition. Per-scorer contamination posture flags. Keys are scorer names; values are enum strings. Required field; may be an empty object for runs not tracking contamination (e.g., eval-toolkit's own test runs).",
136
+ "additionalProperties": {
137
+ "type": "string",
138
+ "enum": ["verified_disjoint", "suspected_contamination", "vendor_black_box", "unknown"]
139
+ }
140
+ },
141
+ "prediction_artifacts": {
142
+ "type": "array",
143
+ "items": {
144
+ "type": "object",
145
+ "required": ["uri", "media_type", "columns"],
146
+ "properties": {
147
+ "uri": {"type": "string", "minLength": 1},
148
+ "media_type": {"type": "string", "minLength": 1},
149
+ "sha256": {"type": "string"},
150
+ "n_rows": {"type": "integer", "minimum": 0},
151
+ "role": {
152
+ "oneOf": [
153
+ {"type": "string", "minLength": 1},
154
+ {
155
+ "type": "array",
156
+ "minItems": 1,
157
+ "items": {"type": "string", "minLength": 1}
158
+ }
159
+ ]
160
+ },
161
+ "metadata": {"type": "object"},
162
+ "columns": {
163
+ "type": "object",
164
+ "required": ["label", "score"],
165
+ "properties": {
166
+ "row_id": {"type": "string", "minLength": 1},
167
+ "content_hash": {"type": "string", "minLength": 1},
168
+ "label": {"type": "string", "minLength": 1},
169
+ "score": {"type": "string", "minLength": 1},
170
+ "scorer": {"type": "string", "minLength": 1},
171
+ "slice": {"type": "string", "minLength": 1},
172
+ "text": {"type": "string", "minLength": 1},
173
+ "provenance": {
174
+ "type": "object",
175
+ "additionalProperties": {"type": "string"}
176
+ }
177
+ },
178
+ "additionalProperties": true
179
+ }
180
+ },
181
+ "additionalProperties": true
182
+ }
183
+ }
184
+ },
185
+ "additionalProperties": true
186
+ }
@@ -0,0 +1,87 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://eval-toolkit/schemas/results.v1.json",
4
+ "version": "1",
5
+ "title": "eval-toolkit RunResult (compact)",
6
+ "description": "Schema for run_dir/results.json (per-row scores stripped). Produced by eval_toolkit.harness.write_run_result.",
7
+ "type": "object",
8
+ "required": ["schema_version", "run_id", "config", "by_slice"],
9
+ "properties": {
10
+ "schema_version": {
11
+ "const": "v1",
12
+ "description": "Stable schema version. Bumps on breaking output changes."
13
+ },
14
+ "run_id": {
15
+ "type": "string",
16
+ "minLength": 1
17
+ },
18
+ "git_sha": {
19
+ "type": ["string", "null"]
20
+ },
21
+ "config": {
22
+ "type": "object",
23
+ "description": "Eval-time config (n_resamples, seed, scorers, slices, paired_diffs, on_scorer_error, optional leakage_report)."
24
+ },
25
+ "by_slice": {
26
+ "type": "object",
27
+ "additionalProperties": {
28
+ "type": "object",
29
+ "description": "Per-slice block: n, n_positive, by_scorer, paired_diffs. Scorer blocks may optionally include transferred_operating_points for validation-fit thresholds applied to this slice."
30
+ }
31
+ },
32
+ "by_fold": {
33
+ "type": "object",
34
+ "description": "Per-fold raw RunResults (populated by evaluate_folded). Empty for non-folded runs.",
35
+ "additionalProperties": true
36
+ },
37
+ "fold_summary": {
38
+ "type": "object",
39
+ "description": "CV-CI summary [slice][scorer][metric] = {mean, ci_low, ci_high, n_folds}. Empty for non-folded runs.",
40
+ "additionalProperties": true
41
+ },
42
+ "claim_report": {
43
+ "type": "object",
44
+ "description": "Optional ClaimReport payload from eval_toolkit.claims.evaluate_claims.",
45
+ "additionalProperties": true
46
+ },
47
+ "prediction_artifacts": {
48
+ "type": "array",
49
+ "description": "Optional references to retained prediction artifacts associated with the result.",
50
+ "items": {"type": "object", "additionalProperties": true}
51
+ },
52
+ "evidence_axes": {
53
+ "type": "array",
54
+ "description": "Optional named axes that scope aggregate evidence.",
55
+ "items": {
56
+ "type": "object",
57
+ "required": ["name", "value"],
58
+ "properties": {
59
+ "name": {"type": "string", "minLength": 1},
60
+ "value": {"type": "string", "minLength": 1}
61
+ },
62
+ "additionalProperties": true
63
+ }
64
+ },
65
+ "pairing_metadata": {
66
+ "type": "object",
67
+ "description": "Optional explicit pairing metadata for paired comparisons.",
68
+ "additionalProperties": true
69
+ },
70
+ "aggregate_evidence": {
71
+ "type": "object",
72
+ "description": "Optional typed aggregate status: inferential, descriptive, diagnostic, or unsupported.",
73
+ "properties": {
74
+ "status": {
75
+ "enum": ["inferential", "descriptive", "diagnostic", "unsupported"]
76
+ }
77
+ },
78
+ "additionalProperties": true
79
+ },
80
+ "threshold_policy": {
81
+ "type": "object",
82
+ "description": "Optional threshold policy metadata naming calibration slice, score column, selector, constraints, and claim-enabled status.",
83
+ "additionalProperties": true
84
+ }
85
+ },
86
+ "additionalProperties": true
87
+ }
@@ -0,0 +1,83 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://eval-toolkit/schemas/results_full.v1.json",
4
+ "version": "1",
5
+ "title": "eval-toolkit RunResult (full)",
6
+ "description": "Schema for run_dir/results_full.json (includes per-row scores). Same top-level shape as results.v1; differs only in that by_slice[*].by_scorer[*].scores arrays are retained.",
7
+ "type": "object",
8
+ "required": ["schema_version", "run_id", "config", "by_slice"],
9
+ "properties": {
10
+ "schema_version": {
11
+ "const": "v1"
12
+ },
13
+ "run_id": {
14
+ "type": "string",
15
+ "minLength": 1
16
+ },
17
+ "git_sha": {
18
+ "type": ["string", "null"]
19
+ },
20
+ "config": {
21
+ "type": "object"
22
+ },
23
+ "by_slice": {
24
+ "type": "object",
25
+ "additionalProperties": {
26
+ "type": "object",
27
+ "description": "Per-slice block. Scorer blocks may optionally include transferred_operating_points for validation-fit thresholds applied to this slice."
28
+ }
29
+ },
30
+ "by_fold": {
31
+ "type": "object",
32
+ "additionalProperties": true
33
+ },
34
+ "fold_summary": {
35
+ "type": "object",
36
+ "additionalProperties": true
37
+ },
38
+ "claim_report": {
39
+ "type": "object",
40
+ "description": "Optional ClaimReport payload from eval_toolkit.claims.evaluate_claims.",
41
+ "additionalProperties": true
42
+ },
43
+ "prediction_artifacts": {
44
+ "type": "array",
45
+ "description": "Optional references to retained prediction artifacts associated with the result.",
46
+ "items": {"type": "object", "additionalProperties": true}
47
+ },
48
+ "evidence_axes": {
49
+ "type": "array",
50
+ "description": "Optional named axes that scope aggregate evidence.",
51
+ "items": {
52
+ "type": "object",
53
+ "required": ["name", "value"],
54
+ "properties": {
55
+ "name": {"type": "string", "minLength": 1},
56
+ "value": {"type": "string", "minLength": 1}
57
+ },
58
+ "additionalProperties": true
59
+ }
60
+ },
61
+ "pairing_metadata": {
62
+ "type": "object",
63
+ "description": "Optional explicit pairing metadata for paired comparisons.",
64
+ "additionalProperties": true
65
+ },
66
+ "aggregate_evidence": {
67
+ "type": "object",
68
+ "description": "Optional typed aggregate status: inferential, descriptive, diagnostic, or unsupported.",
69
+ "properties": {
70
+ "status": {
71
+ "enum": ["inferential", "descriptive", "diagnostic", "unsupported"]
72
+ }
73
+ },
74
+ "additionalProperties": true
75
+ },
76
+ "threshold_policy": {
77
+ "type": "object",
78
+ "description": "Optional threshold policy metadata naming calibration slice, score column, selector, constraints, and claim-enabled status.",
79
+ "additionalProperties": true
80
+ }
81
+ },
82
+ "additionalProperties": true
83
+ }
eval_toolkit/seeds.py ADDED
@@ -0,0 +1,119 @@
1
+ """Global seed-setting for reproducibility.
2
+
3
+ Public API: :func:`set_global_seeds`. Sets ``PYTHONHASHSEED``, ``random``,
4
+ ``numpy``, and optionally ``torch`` (with ``cudnn.deterministic=True``).
5
+ Torch is a soft dependency — toolkit installs without it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import random
12
+ import warnings
13
+
14
+ import numpy as np
15
+
16
+ __all__ = ["set_global_seeds"]
17
+
18
+
19
+ def set_global_seeds(seed: int, *, strict_torch_determinism: bool = False) -> None:
20
+ """Pin random / numpy / torch seeds + enable deterministic CUDA where possible.
21
+
22
+ Sets the four sources of nondeterminism that any Python-flavored ML
23
+ pipeline can practically control: ``PYTHONHASHSEED`` (string-hash
24
+ salt), the stdlib ``random`` module, ``numpy``'s legacy global RNG,
25
+ and ``torch`` (CPU + CUDA + cuDNN flags) when torch is importable.
26
+
27
+ Matches PyTorch Lightning's :func:`seed_everything` discipline.
28
+
29
+ Parameters
30
+ ----------
31
+ seed : int
32
+ Non-negative seed value.
33
+ strict_torch_determinism : bool, optional
34
+ If ``True``, also call ``torch.use_deterministic_algorithms(True)``
35
+ to make every torch op raise on nondeterministic kernels (vs. the
36
+ default cuDNN-only flags). Useful when bit-exact reproducibility
37
+ is required across runs. Has no effect if torch is not installed.
38
+ Default ``False``.
39
+
40
+ Raises
41
+ ------
42
+ TypeError
43
+ If ``seed`` is not an ``int``.
44
+ ValueError
45
+ If ``seed`` is negative.
46
+ RuntimeError
47
+ If ``strict_torch_determinism=True`` is requested but ``torch`` is
48
+ not installed.
49
+
50
+ Notes
51
+ -----
52
+ Full determinism on CUDA is not always achievable — some kernels lack
53
+ deterministic implementations. Documented residual variance can be
54
+ handled by reporting multi-seed CIs rather than relying on bit-exact
55
+ reproducibility.
56
+
57
+ ``PYTHONHASHSEED`` is set in the *current* process's environment but
58
+ only takes effect for child processes (the current interpreter has
59
+ already initialized its hash randomization). To get deterministic
60
+ string hashing in the current run, set ``PYTHONHASHSEED`` from the
61
+ shell *before* launching Python; this function emits a UserWarning
62
+ when the variable is already set to a different value.
63
+
64
+ Torch is imported lazily inside the function. If ``torch`` is not
65
+ installed, the random + numpy seeds + ``PYTHONHASHSEED`` are still
66
+ set.
67
+
68
+ Examples
69
+ --------
70
+ >>> import numpy as np
71
+ >>> set_global_seeds(42)
72
+ >>> a1 = np.random.rand(5)
73
+ >>> set_global_seeds(42)
74
+ >>> a2 = np.random.rand(5)
75
+ >>> bool(np.all(a1 == a2))
76
+ True
77
+
78
+ See Also
79
+ --------
80
+ `pytorch-lightning.seed_everything <https://lightning.ai/docs/pytorch/stable/common/seed.html>`_ :
81
+ Reference for the strict_torch_determinism semantics.
82
+ """
83
+ if not isinstance(seed, int):
84
+ raise TypeError(f"seed must be int, got {type(seed).__name__}")
85
+ if seed < 0:
86
+ raise ValueError(f"seed must be non-negative, got {seed}")
87
+
88
+ target = str(seed)
89
+ existing = os.environ.get("PYTHONHASHSEED")
90
+ if existing is not None and existing != target:
91
+ warnings.warn(
92
+ f"PYTHONHASHSEED was already set to {existing!r}; overwriting to "
93
+ f"{target!r}. The current Python process's hash randomization is "
94
+ f"unaffected — set PYTHONHASHSEED before launching Python for "
95
+ f"in-process determinism.",
96
+ UserWarning,
97
+ stacklevel=2,
98
+ )
99
+ os.environ["PYTHONHASHSEED"] = target
100
+
101
+ random.seed(seed)
102
+ np.random.seed(seed)
103
+
104
+ try:
105
+ import torch # type: ignore[import-not-found] # noqa: PLC0415
106
+ except ImportError:
107
+ if strict_torch_determinism:
108
+ raise RuntimeError(
109
+ "strict_torch_determinism=True requested but torch is not installed"
110
+ ) from None
111
+ return
112
+
113
+ torch.manual_seed(seed)
114
+ if torch.cuda.is_available():
115
+ torch.cuda.manual_seed_all(seed)
116
+ torch.backends.cudnn.deterministic = True
117
+ torch.backends.cudnn.benchmark = False
118
+ if strict_torch_determinism:
119
+ torch.use_deterministic_algorithms(True)