zyexp 0.1.0__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.
zyexp/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ from .core import (
2
+ ArtifactRecord,
3
+ CheckpointManager,
4
+ CheckpointRecord,
5
+ Group,
6
+ JsonValue,
7
+ Last,
8
+ Maximum,
9
+ MetricPoint,
10
+ Minimum,
11
+ RecordNode,
12
+ Reducer,
13
+ RelationRecord,
14
+ Run,
15
+ Sum,
16
+ Trial,
17
+ TrialMetrics,
18
+ WeightedMean,
19
+ get_schema,
20
+ iter_metrics,
21
+ iter_node_states,
22
+ iter_records,
23
+ load_run,
24
+ open_run,
25
+ repair_interrupted_run,
26
+ validate_report,
27
+ validate_run,
28
+ )
29
+
30
+ __all__ = [
31
+ 'ArtifactRecord',
32
+ 'CheckpointManager',
33
+ 'CheckpointRecord',
34
+ 'Group',
35
+ 'JsonValue',
36
+ 'Last',
37
+ 'Maximum',
38
+ 'MetricPoint',
39
+ 'Minimum',
40
+ 'RecordNode',
41
+ 'Reducer',
42
+ 'RelationRecord',
43
+ 'Run',
44
+ 'Sum',
45
+ 'Trial',
46
+ 'TrialMetrics',
47
+ 'WeightedMean',
48
+ 'get_schema',
49
+ 'iter_metrics',
50
+ 'iter_node_states',
51
+ 'iter_records',
52
+ 'load_run',
53
+ 'open_run',
54
+ 'repair_interrupted_run',
55
+ 'validate_report',
56
+ 'validate_run',
57
+ ]
zyexp/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
zyexp/_skill.py ADDED
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import re
5
+ from pathlib import Path
6
+
7
+ _SKILL_DIRECTORY = Path(__file__).parent / 'skills' / 'zyexp'
8
+ _FRONTMATTER = re.compile(r'\A---\r?\n(?P<header>.*?)\r?\n---\r?\n(?P<body>.*)\Z', re.DOTALL)
9
+ _NAME = re.compile(r'^name:\s*["\']?(?P<name>[a-z0-9-]+)["\']?\s*$', re.MULTILINE)
10
+
11
+
12
+ def render_skill() -> str:
13
+ skill_file = (_SKILL_DIRECTORY / 'SKILL.md').resolve()
14
+ skill_text = skill_file.read_text(encoding='utf-8')
15
+ frontmatter = _FRONTMATTER.fullmatch(skill_text)
16
+ if frontmatter is None:
17
+ raise ValueError(f'skill has no valid frontmatter: {skill_file}')
18
+
19
+ name_match = _NAME.search(frontmatter.group('header'))
20
+ if name_match is None:
21
+ raise ValueError(f'skill frontmatter has no valid name: {skill_file}')
22
+
23
+ skill_directory = skill_file.parent
24
+ resources = sorted(
25
+ path.relative_to(skill_directory).as_posix()
26
+ for path in skill_directory.rglob('*')
27
+ if path.is_file() and path != skill_file
28
+ )
29
+ resource_lines = '\n'.join(
30
+ f' <file>{html.escape(resource)}</file>' for resource in resources
31
+ )
32
+
33
+ name = html.escape(name_match.group('name'), quote=True)
34
+ location = html.escape(str(skill_file), quote=True)
35
+ directory = html.escape(str(skill_directory), quote=True)
36
+ body = frontmatter.group('body').rstrip('\r\n')
37
+
38
+ return (
39
+ f'<skill_content name="{name}" location="{location}">\n'
40
+ f'{body}\n\n'
41
+ f'Skill directory: {directory}\n'
42
+ 'Relative paths in this skill are relative to the skill directory.\n\n'
43
+ '<skill_resources>\n'
44
+ f'{resource_lines}\n'
45
+ '</skill_resources>\n'
46
+ '</skill_content>\n'
47
+ )
@@ -0,0 +1,3 @@
1
+ """Optional framework descriptions that never control framework execution."""
2
+
3
+ __all__: list[str] = []
@@ -0,0 +1,81 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable, Mapping
4
+ from typing import Any, cast
5
+
6
+ from zyexp.core.records import JsonValue, to_json_value
7
+
8
+
9
+ def describe_datasets(**datasets: Any) -> dict[str, JsonValue]:
10
+ return {name: describe_dataset(dataset) for name, dataset in datasets.items()}
11
+
12
+
13
+ def describe_dataset(dataset: Any) -> dict[str, JsonValue]:
14
+ description: dict[str, JsonValue] = {'type': _qualified_name(dataset)}
15
+ try:
16
+ description['samples'] = len(dataset)
17
+ except (TypeError, AttributeError):
18
+ pass
19
+ return description
20
+
21
+
22
+ def describe_module(module: Any) -> dict[str, JsonValue]:
23
+ description: dict[str, JsonValue] = {'type': _qualified_name(module)}
24
+ named_parameters = getattr(module, 'named_parameters', None)
25
+ if not callable(named_parameters):
26
+ return description
27
+
28
+ total = 0
29
+ trainable = 0
30
+ shapes: dict[str, JsonValue] = {}
31
+ parameters = cast(Iterable[tuple[str, Any]], named_parameters())
32
+ for name, parameter in parameters:
33
+ count = int(parameter.numel())
34
+ total += count
35
+ if bool(getattr(parameter, 'requires_grad', False)):
36
+ trainable += count
37
+ shapes[str(name)] = list(parameter.shape)
38
+ description.update(
39
+ {
40
+ 'parameter_count': total,
41
+ 'trainable_parameter_count': trainable,
42
+ 'parameter_shapes': shapes,
43
+ }
44
+ )
45
+ return description
46
+
47
+
48
+ def describe_optimizer(optimizer: Any) -> dict[str, JsonValue]:
49
+ description: dict[str, JsonValue] = {'type': _qualified_name(optimizer)}
50
+ defaults = getattr(optimizer, 'defaults', None)
51
+ if isinstance(defaults, Mapping):
52
+ description['defaults'] = _safe_mapping(defaults)
53
+
54
+ groups = getattr(optimizer, 'param_groups', None)
55
+ if isinstance(groups, list):
56
+ description['parameter_groups'] = [
57
+ {
58
+ str(name): _safe_value(value)
59
+ for name, value in group.items()
60
+ if name != 'params'
61
+ }
62
+ for group in groups
63
+ if isinstance(group, Mapping)
64
+ ]
65
+ return description
66
+
67
+
68
+ def _safe_mapping(values: Mapping[Any, Any]) -> dict[str, JsonValue]:
69
+ return {str(name): _safe_value(value) for name, value in values.items()}
70
+
71
+
72
+ def _safe_value(value: Any) -> JsonValue:
73
+ try:
74
+ return to_json_value(value, path='$.trainer')
75
+ except TypeError:
76
+ return {'type': _qualified_name(value)}
77
+
78
+
79
+ def _qualified_name(value: Any) -> str:
80
+ value_type = type(value)
81
+ return f'{value_type.__module__}.{value_type.__qualname__}'
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ from collections.abc import Mapping
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from zyexp.core.records import JsonValue, to_json_value
9
+
10
+
11
+ def describe_arrays(**splits: tuple[Any, Any]) -> dict[str, JsonValue]:
12
+ """Describe and content-hash feature/label arrays without retaining them."""
13
+ return {
14
+ name: {
15
+ 'features': _array_identity(features),
16
+ 'labels': _array_identity(labels),
17
+ }
18
+ for name, (features, labels) in splits.items()
19
+ }
20
+
21
+
22
+ def describe_estimator(estimator: Any) -> dict[str, JsonValue]:
23
+ """Record estimator type and shallow constructor parameters without repr()."""
24
+ description: dict[str, JsonValue] = {'type': _qualified_name(estimator)}
25
+ get_params = getattr(estimator, 'get_params', None)
26
+ if callable(get_params):
27
+ parameters = get_params(deep=False)
28
+ if isinstance(parameters, Mapping):
29
+ description['parameters'] = {
30
+ str(name): _describe_parameter(value)
31
+ for name, value in parameters.items()
32
+ }
33
+ return description
34
+
35
+
36
+ def _array_identity(array: Any) -> dict[str, JsonValue]:
37
+ import numpy as np
38
+
39
+ values = np.asarray(array)
40
+ contiguous = np.ascontiguousarray(values)
41
+ return {
42
+ 'shape': list(values.shape),
43
+ 'dtype': str(values.dtype),
44
+ 'sha256': hashlib.sha256(contiguous.tobytes()).hexdigest(),
45
+ }
46
+
47
+
48
+ def _describe_parameter(value: Any) -> JsonValue:
49
+ try:
50
+ return to_json_value(value, path='$.estimator.parameters')
51
+ except TypeError:
52
+ pass
53
+ if isinstance(value, Mapping):
54
+ return {str(name): _describe_parameter(item) for name, item in value.items()}
55
+ if isinstance(value, (list, tuple)):
56
+ return [_describe_parameter(item) for item in value]
57
+ if isinstance(value, Path):
58
+ return str(value)
59
+ return {'type': _qualified_name(value)}
60
+
61
+
62
+ def _qualified_name(value: Any) -> str:
63
+ value_type = type(value)
64
+ return f'{value_type.__module__}.{value_type.__qualname__}'
zyexp/cli.py ADDED
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from ._skill import render_skill
11
+ from .core.query import iter_records
12
+ from .core.recovery import repair_interrupted_run
13
+ from .core.report import get_schema, load_run
14
+ from .core.validation import validate_run
15
+
16
+
17
+ def _write_json(value: Any, *, file: Any | None = None) -> None:
18
+ output = sys.stdout if file is None else file
19
+ json.dump(value, output, ensure_ascii=False, indent=2, sort_keys=True)
20
+ output.write('\n')
21
+
22
+
23
+ def _build_parser() -> argparse.ArgumentParser:
24
+ parser = argparse.ArgumentParser(prog='zyexp')
25
+ commands = parser.add_subparsers(dest='command', required=True)
26
+
27
+ commands.add_parser('skill', help='Print the bundled Agent Skill')
28
+ commands.add_parser(
29
+ 'sourcecode', help='Print the installed zyexp source directory'
30
+ )
31
+
32
+ schema_parser = commands.add_parser('schema', help='Print a bundled JSON Schema')
33
+ schema_parser.add_argument('--kind', choices=('run', 'record'), default='run')
34
+
35
+ inspect_parser = commands.add_parser(
36
+ 'inspect', help='Print a materialized Run report'
37
+ )
38
+ inspect_parser.add_argument('path', type=Path)
39
+
40
+ validate_parser = commands.add_parser('validate', help='Validate a Run')
41
+ validate_parser.add_argument('path', type=Path)
42
+ validate_parser.add_argument(
43
+ '--verify-artifacts',
44
+ action='store_true',
45
+ help='Recompute managed artifact and checkpoint hashes',
46
+ )
47
+
48
+ repair_parser = commands.add_parser(
49
+ 'repair', help='Mark abandoned running nodes as interrupted'
50
+ )
51
+ repair_parser.add_argument('path', type=Path)
52
+
53
+ records_parser = commands.add_parser('records', help='Read node records')
54
+ records_parser.add_argument('path', type=Path)
55
+ records_parser.add_argument('--node')
56
+ records_parser.add_argument('--type', dest='record_type')
57
+ records_parser.add_argument('--name')
58
+ return parser
59
+
60
+
61
+ def main(argv: Sequence[str] | None = None) -> int:
62
+ parser = _build_parser()
63
+ args = parser.parse_args(argv)
64
+ try:
65
+ if args.command == 'skill':
66
+ sys.stdout.write(render_skill())
67
+ return 0
68
+ if args.command == 'sourcecode':
69
+ print(Path(__file__).resolve().parent)
70
+ return 0
71
+ if args.command == 'schema':
72
+ _write_json(get_schema(args.kind))
73
+ return 0
74
+ if args.command == 'inspect':
75
+ _write_json(load_run(args.path))
76
+ return 0
77
+ if args.command == 'validate':
78
+ issues = validate_run(args.path, verify_artifacts=args.verify_artifacts)
79
+ _write_json({'valid': not issues, 'issues': issues})
80
+ return 0 if not issues else 1
81
+ if args.command == 'repair':
82
+ _write_json(repair_interrupted_run(args.path))
83
+ return 0
84
+ if args.command == 'records':
85
+ records = list(
86
+ iter_records(
87
+ args.path,
88
+ node_path=args.node,
89
+ record_type=args.record_type,
90
+ name=args.name,
91
+ )
92
+ )
93
+ _write_json({'records': records})
94
+ return 0
95
+ parser.error(f'unknown command: {args.command}')
96
+ except Exception as error: # noqa: BLE001 - CLI boundary returns structured errors
97
+ _write_json(
98
+ {'error': {'type': type(error).__name__, 'message': str(error)}},
99
+ file=sys.stderr,
100
+ )
101
+ return 2
102
+ return 2
103
+
104
+
105
+ if __name__ == '__main__':
106
+ raise SystemExit(main())
zyexp/core/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ from .aggregation import Last, Maximum, Minimum, Reducer, Sum, WeightedMean
2
+ from .checkpoints import CheckpointManager, CheckpointRecord
3
+ from .metrics import MetricPoint, TrialMetrics
4
+ from .query import iter_metrics, iter_node_states, iter_records
5
+ from .records import ArtifactRecord, JsonValue, RelationRecord
6
+ from .recovery import repair_interrupted_run
7
+ from .report import get_schema, load_run
8
+ from .session import Group, RecordNode, Run, Trial, open_run
9
+ from .validation import validate_report, validate_run
10
+
11
+ __all__ = [
12
+ 'ArtifactRecord',
13
+ 'CheckpointManager',
14
+ 'CheckpointRecord',
15
+ 'Group',
16
+ 'JsonValue',
17
+ 'Last',
18
+ 'Maximum',
19
+ 'MetricPoint',
20
+ 'Minimum',
21
+ 'RecordNode',
22
+ 'Reducer',
23
+ 'RelationRecord',
24
+ 'Run',
25
+ 'Sum',
26
+ 'Trial',
27
+ 'TrialMetrics',
28
+ 'WeightedMean',
29
+ 'get_schema',
30
+ 'iter_metrics',
31
+ 'iter_node_states',
32
+ 'iter_records',
33
+ 'load_run',
34
+ 'open_run',
35
+ 'repair_interrupted_run',
36
+ 'validate_report',
37
+ 'validate_run',
38
+ ]
@@ -0,0 +1,148 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Any, Protocol
5
+
6
+ from .records import JsonValue
7
+
8
+
9
+ class Reducer(Protocol):
10
+ def update(self, value: Any, *, weight: float | None = None) -> None: ...
11
+
12
+ def compute(self) -> Any: ...
13
+
14
+ def metadata(self) -> dict[str, JsonValue]: ...
15
+
16
+
17
+ def _finite_number(value: Any, *, field: str) -> float:
18
+ if isinstance(value, (bool, str, bytes)):
19
+ raise TypeError(f'{field} must be a real number, got {type(value).__name__}')
20
+ try:
21
+ number = float(value)
22
+ except (TypeError, ValueError) as error:
23
+ raise TypeError(
24
+ f'{field} must be a real number, got {type(value).__name__}'
25
+ ) from error
26
+ if not math.isfinite(number):
27
+ raise ValueError(f'{field} must be finite')
28
+ return number
29
+
30
+
31
+ class WeightedMean:
32
+ def __init__(self) -> None:
33
+ self._weighted_sum = 0.0
34
+ self._weight = 0.0
35
+ self._count = 0
36
+
37
+ def update(self, value: Any, *, weight: float | None = None) -> None:
38
+ number = _finite_number(value, field='metric value')
39
+ numeric_weight = _finite_number(
40
+ 1.0 if weight is None else weight, field='metric weight'
41
+ )
42
+ if numeric_weight < 0:
43
+ raise ValueError('metric weight must be non-negative')
44
+ self._weighted_sum += number * numeric_weight
45
+ self._weight += numeric_weight
46
+ self._count += 1
47
+
48
+ def compute(self) -> float:
49
+ if self._weight == 0:
50
+ raise ValueError('weighted mean requires a positive total weight')
51
+ return self._weighted_sum / self._weight
52
+
53
+ def metadata(self) -> dict[str, JsonValue]:
54
+ return {'kind': 'weighted_mean', 'updates': self._count, 'weight': self._weight}
55
+
56
+
57
+ class Sum:
58
+ def __init__(self) -> None:
59
+ self._total = 0.0
60
+ self._count = 0
61
+
62
+ def update(self, value: Any, *, weight: float | None = None) -> None:
63
+ del weight
64
+ self._total += _finite_number(value, field='metric value')
65
+ self._count += 1
66
+
67
+ def compute(self) -> float:
68
+ return self._total
69
+
70
+ def metadata(self) -> dict[str, JsonValue]:
71
+ return {'kind': 'sum', 'updates': self._count}
72
+
73
+
74
+ class Minimum:
75
+ def __init__(self) -> None:
76
+ self._value: float | None = None
77
+
78
+ def update(self, value: Any, *, weight: float | None = None) -> None:
79
+ del weight
80
+ number = _finite_number(value, field='metric value')
81
+ self._value = number if self._value is None else min(self._value, number)
82
+
83
+ def compute(self) -> float:
84
+ if self._value is None:
85
+ raise ValueError('minimum requires at least one value')
86
+ return self._value
87
+
88
+ def metadata(self) -> dict[str, JsonValue]:
89
+ return {'kind': 'min'}
90
+
91
+
92
+ class Maximum:
93
+ def __init__(self) -> None:
94
+ self._value: float | None = None
95
+
96
+ def update(self, value: Any, *, weight: float | None = None) -> None:
97
+ del weight
98
+ number = _finite_number(value, field='metric value')
99
+ self._value = number if self._value is None else max(self._value, number)
100
+
101
+ def compute(self) -> float:
102
+ if self._value is None:
103
+ raise ValueError('maximum requires at least one value')
104
+ return self._value
105
+
106
+ def metadata(self) -> dict[str, JsonValue]:
107
+ return {'kind': 'max'}
108
+
109
+
110
+ class Last:
111
+ def __init__(self) -> None:
112
+ self._has_value = False
113
+ self._value: Any = None
114
+
115
+ def update(self, value: Any, *, weight: float | None = None) -> None:
116
+ del weight
117
+ self._has_value = True
118
+ self._value = value
119
+
120
+ def compute(self) -> Any:
121
+ if not self._has_value:
122
+ raise ValueError('last requires at least one value')
123
+ return self._value
124
+
125
+ def metadata(self) -> dict[str, JsonValue]:
126
+ return {'kind': 'last'}
127
+
128
+
129
+ _REDUCERS: dict[str, type[WeightedMean | Sum | Minimum | Maximum | Last]] = {
130
+ 'weighted_mean': WeightedMean,
131
+ 'sum': Sum,
132
+ 'min': Minimum,
133
+ 'max': Maximum,
134
+ 'last': Last,
135
+ }
136
+
137
+
138
+ def create_reducer(kind: str) -> Reducer:
139
+ try:
140
+ reducer_type = _REDUCERS[kind]
141
+ except KeyError as error:
142
+ expected = ', '.join(sorted(_REDUCERS))
143
+ raise ValueError(f'unknown aggregate {kind!r}; expected one of: {expected}') from error
144
+ return reducer_type()
145
+
146
+
147
+ def aggregate_kinds() -> tuple[str, ...]:
148
+ return tuple(sorted(_REDUCERS))