wabdalm commited on
Commit
69928d6
·
verified ·
1 Parent(s): 6488989

Release AS2 framework with Hydra-selected instantiations

Browse files

Publish the reviewed generic AS2 framework with Visual Sudoku as the first bundled instantiation, selected pretrained weights, uv workflows, and extension documentation. Preserve selected weights and disclose the deferred fresh-training discrepancy.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -34
  2. .gitignore +9 -0
  3. .python-version +1 -0
  4. LICENSE +158 -0
  5. README.md +170 -0
  6. THIRD_PARTY_NOTICES.md +10 -0
  7. configs/config.yaml +24 -0
  8. configs/dataset/sudoku.yaml +13 -0
  9. configs/evaluator/sudoku.yaml +9 -0
  10. configs/instantiation/sudoku.yaml +85 -0
  11. configs/logging/default.yaml +8 -0
  12. configs/model/perception_only_sudoku.yaml +13 -0
  13. configs/model/softasp_sudoku.yaml +19 -0
  14. configs/paths/local.yaml +5 -0
  15. configs/predict.yaml +12 -0
  16. configs/preprocessing/sudoku.yaml +14 -0
  17. configs/sudoku_from_scratch.yaml +3 -0
  18. configs/sudoku_release1.yaml +36 -0
  19. configs/train_scratch.yaml +10 -0
  20. configs/trainer/default.yaml +47 -0
  21. configs/trainer/sudoku.yaml +45 -0
  22. configs/trainer/sudoku_softasp.yaml +46 -0
  23. docs/instantiations.md +126 -0
  24. examples/sudoku.npz +3 -0
  25. models/sudoku/as2.pt +3 -0
  26. models/sudoku/metadata.json +14 -0
  27. models/sudoku/model.json +23 -0
  28. packages/softasp-core/LICENSE +158 -0
  29. packages/softasp-core/pyproject.toml +24 -0
  30. packages/softasp-core/src/softasp_core/__init__.py +3 -0
  31. packages/softasp-core/src/softasp_core/config/__init__.py +29 -0
  32. packages/softasp-core/src/softasp_core/config/loader.py +45 -0
  33. packages/softasp-core/src/softasp_core/config/schemas.py +165 -0
  34. packages/softasp-core/src/softasp_core/config/validation.py +103 -0
  35. packages/softasp-core/src/softasp_core/data/__init__.py +16 -0
  36. packages/softasp-core/src/softasp_core/data/augmentations.py +106 -0
  37. packages/softasp-core/src/softasp_core/data/base_downloader.py +74 -0
  38. packages/softasp-core/src/softasp_core/data/base_preprocessor.py +136 -0
  39. packages/softasp-core/src/softasp_core/data/collate.py +38 -0
  40. packages/softasp-core/src/softasp_core/data/hdf5_dataset.py +114 -0
  41. packages/softasp-core/src/softasp_core/distributed/__init__.py +23 -0
  42. packages/softasp-core/src/softasp_core/distributed/distributed.py +129 -0
  43. packages/softasp-core/src/softasp_core/distributed/eval_sampler.py +67 -0
  44. packages/softasp-core/src/softasp_core/evaluation/__init__.py +11 -0
  45. packages/softasp-core/src/softasp_core/evaluation/evaluator.py +92 -0
  46. packages/softasp-core/src/softasp_core/evaluation/metrics.py +320 -0
  47. packages/softasp-core/src/softasp_core/tracking/__init__.py +5 -0
  48. packages/softasp-core/src/softasp_core/tracking/aim_tracker.py +159 -0
  49. packages/softasp-core/src/softasp_core/training/__init__.py +14 -0
  50. packages/softasp-core/src/softasp_core/training/checkpointing.py +195 -0
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.pt filter=lfs diff=lfs merge=lfs -text
2
+ examples/sudoku.npz filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .aim/
5
+ /data/
6
+ /outputs/
7
+ /dist/
8
+ .ruff_cache/
9
+ .pytest_cache/
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
LICENSE ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution-NonCommercial 4.0 International
2
+
3
+ Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
4
+
5
+ Using Creative Commons Public Licenses
6
+
7
+ Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
8
+
9
+ Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
10
+
11
+ Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
12
+
13
+ Creative Commons Attribution-NonCommercial 4.0 International Public License
14
+
15
+ By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
16
+
17
+ Section 1 – Definitions.
18
+
19
+ a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
20
+
21
+ b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
22
+
23
+ c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
24
+
25
+ d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
26
+
27
+ e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
28
+
29
+ f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
30
+
31
+ g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
32
+
33
+ h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
34
+
35
+ i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
36
+
37
+ j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
38
+
39
+ k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
40
+
41
+ l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
42
+
43
+ Section 2 – Scope.
44
+
45
+ a. License grant.
46
+
47
+ 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
48
+
49
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
50
+
51
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
52
+
53
+ 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
54
+
55
+ 3. Term. The term of this Public License is specified in Section 6(a).
56
+
57
+ 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
58
+
59
+ 5. Downstream recipients.
60
+
61
+ A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
62
+
63
+ B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
64
+
65
+ 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
66
+
67
+ b. Other rights.
68
+
69
+ 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
70
+
71
+ 2. Patent and trademark rights are not licensed under this Public License.
72
+
73
+ 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
74
+
75
+ Section 3 – License Conditions.
76
+
77
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
78
+
79
+ a. Attribution.
80
+
81
+ 1. If You Share the Licensed Material (including in modified form), You must:
82
+
83
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
84
+
85
+ i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
86
+
87
+ ii. a copyright notice;
88
+
89
+ iii. a notice that refers to this Public License;
90
+
91
+ iv. a notice that refers to the disclaimer of warranties;
92
+
93
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
94
+
95
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
96
+
97
+ C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
98
+
99
+ 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
100
+
101
+ 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
102
+
103
+ 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
104
+
105
+ Section 4 – Sui Generis Database Rights.
106
+
107
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
108
+
109
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
110
+
111
+ b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
112
+
113
+ c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
114
+ For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
115
+
116
+ Section 5 – Disclaimer of Warranties and Limitation of Liability.
117
+
118
+ a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
119
+
120
+ b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
121
+
122
+ c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
123
+
124
+ Section 6 – Term and Termination.
125
+
126
+ a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
127
+
128
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
129
+
130
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
131
+
132
+ 2. upon express reinstatement by the Licensor.
133
+
134
+ For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
135
+
136
+ c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
137
+
138
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
139
+
140
+ Section 7 – Other Terms and Conditions.
141
+
142
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
143
+
144
+ b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
145
+
146
+ Section 8 – Interpretation.
147
+
148
+ a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
149
+
150
+ b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
151
+
152
+ c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
153
+
154
+ d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
155
+
156
+ Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
157
+
158
+ Creative Commons may be contacted at creativecommons.org.
README.md CHANGED
@@ -1,3 +1,173 @@
1
  ---
2
  license: cc-by-nc-4.0
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: cc-by-nc-4.0
3
+ library_name: pytorch
4
+ tags:
5
+ - sudoku
6
+ - neuro-symbolic
7
+ - answer-set-programming
8
+ - attention
9
+ - pytorch
10
  ---
11
+
12
+ # AS²: Attention-Based Soft Answer Set Programming
13
+
14
+ AS² is a generic attention-based soft answer set framework. See the
15
+ [paper](https://arxiv.org/html/2603.18436v1) for the method and experiments.
16
+ The framework combines configurable perception or input encoders, soft symbolic
17
+ representations, attention-based reasoning, task heads, and differentiable
18
+ constraint objectives.
19
+
20
+ **Visual Sudoku is the first bundled instantiation and benchmark.** Its data,
21
+ board geometry, constraints, objectives, metrics and training recipe are supplied
22
+ by adapters selected through `configs/instantiation/sudoku.yaml`. The included
23
+ weights and example belong to that instantiation; they do not define AS²'s scope.
24
+ Sudoku predictions use raw neural argmax without symbolic repair.
25
+
26
+ The same train, predict, evaluate and from-scratch commands select instantiations
27
+ through Hydra. **MNIST Addition and CLEVR-Hans are planned future instantiations**;
28
+ their runnable implementations are not included in this release.
29
+ See [Adding an instantiation](docs/instantiations.md) for the extension contract.
30
+ Each instantiation provides its declarative constraints and their differentiable
31
+ implementation. An automatic constraint compiler is not included or required.
32
+
33
+ ## Install
34
+
35
+ Use Python 3.12+ and [uv](https://docs.astral.sh/uv/).
36
+ Download this entire repository, including the actual model file (not a Git LFS
37
+ pointer), and run commands from its root:
38
+
39
+ ```bash
40
+ uv sync --locked
41
+ uv run --locked softasp-predict instantiation=sudoku
42
+ ```
43
+
44
+ The first command installs the three local packages and their locked dependencies.
45
+ PyTorch installation can be large; CUDA training requires a compatible NVIDIA
46
+ driver. Inference works on CPU; `device=auto` selects CUDA when available.
47
+
48
+ ## Predict with the Sudoku instantiation
49
+
50
+ The included example contains one MNIST-derived Sudoku board and its clue mask.
51
+ No solution labels are supplied to prediction. The command above writes
52
+ `outputs/prediction.json`, containing digits **1–9** and a structural-validity
53
+ flag. Structural validity is not an accuracy measurement. Existing prediction
54
+ files are never overwritten; choose a fresh output path for another run.
55
+
56
+ ```bash
57
+ uv run --locked softasp-predict instantiation=sudoku input=examples/sudoku.npz \
58
+ checkpoint=models/sudoku/as2.pt output=outputs/my-prediction.json device=cpu
59
+ ```
60
+
61
+ For your own inputs, create an NPZ file with:
62
+ - `images`: shape `(N,252,252,1)`, uint8 in 0–255 or float32 in 0–1.
63
+ - `puzzle_mask`: shape `(N,81)`, 1 for visible clues and 0 for blanks.
64
+
65
+ Cells are in row-major order. Use white digit strokes on black backgrounds;
66
+ blank cells are black. The model expects aligned cell images, not a photograph
67
+ of a printed grid. Raw predictions can violate Sudoku constraints.
68
+
69
+ ## Train the Sudoku instantiation from scratch
70
+
71
+ This command downloads MNIST, generates 9,000/1,000/1,000 train/validation/test
72
+ boards, trains a fresh CNN and then AS², and evaluates the resulting model.
73
+ It does not read the shipped weights.
74
+
75
+ ```bash
76
+ uv run --locked softasp-train-scratch instantiation=sudoku pipeline.name=my-run
77
+ ```
78
+
79
+ Both stages allow up to 200 epochs with patience 50; seed is 42 and batch size
80
+ is 32. The portable default is float32. For a GPU supporting bf16, the recorded
81
+ training recipe uses:
82
+
83
+ ```bash
84
+ uv run --locked softasp-train-scratch instantiation=sudoku pipeline.name=my-gpu-run trainer.precision=bf16
85
+ ```
86
+
87
+ The backbone inherits the chosen precision. Hydra controls all paths:
88
+
89
+ ```bash
90
+ uv run --locked softasp-train-scratch instantiation=sudoku pipeline.name=my-run \
91
+ paths.data_root=/path/to/data paths.output_dir=/path/to/outputs \
92
+ paths.model_dir=/path/to/models
93
+ ```
94
+
95
+ For a small functionality check, use a fresh run name:
96
+
97
+ ```bash
98
+ uv run --locked softasp-train-scratch instantiation=sudoku pipeline.name=smoke \
99
+ preprocessing.subset_size=2 trainer.epochs=1 backbone.trainer.epochs=1 \
100
+ trainer.batch_size_per_gpu=2 backbone.trainer.batch_size_per_gpu=2 \
101
+ trainer.scheduler.warmup_steps=0 backbone.trainer.scheduler.warmup_steps=0 \
102
+ trainer.num_workers=0 backbone.trainer.num_workers=0 \
103
+ trainer.persistent_workers=false backbone.trainer.persistent_workers=false
104
+ ```
105
+
106
+ This small run is not an accuracy benchmark. Every run records a manifest,
107
+ resolved configuration, data hashes, checkpoints, and Aim metrics under your
108
+ output directories. Fresh run/model directories are required; existing runs
109
+ are not silently resumed or replaced. Models are saved under
110
+ `models/sudoku/<run-name>/`; the manifest is under
111
+ `outputs/sudoku/from_scratch/<run-name>/`.
112
+
113
+ To reuse downloaded MNIST, set `pipeline.download=false` and
114
+ `paths.raw_data_root=/path/containing/mnist`. A deliberate existing-backbone
115
+ workflow is also available through `softasp-train`, with
116
+ `model.pretrained_from` and explicit dataset identity; inference never trains.
117
+
118
+ ## Evaluate a dataset
119
+
120
+ Use the HDF5 path and SHA256 recorded in your training manifest. The file must
121
+ contain train, val, and test groups with images, labels (digits encoded 0–8),
122
+ and puzzle_mask. No full dataset is included.
123
+
124
+ ```bash
125
+ uv run --locked softasp-evaluate instantiation=sudoku dataset.splits=[test] \
126
+ data_artifact.path=/path/to/dataset.h5 data_artifact.sha256=YOUR_SHA256 \
127
+ data_artifact.protocol_id=null evaluator.checkpoint=models/sudoku/as2.pt \
128
+ paths.output_dir=outputs/my-evaluation
129
+ ```
130
+
131
+ The evaluator writes raw predictions, exact metric counts, and provenance to a
132
+ fresh output directory. It uses float32 inference without autocast, oracle
133
+ labels, refinement, or repair.
134
+
135
+ ## Framework layout
136
+
137
+ - `packages/softasp-solver/.../components/`: encoders, evidence policies, structural
138
+ representations and attention composition.
139
+ - `packages/softasp-solver/.../constraints/`: shared differentiable operators and residuals.
140
+ - `packages/softasp-core/`: configuration, training, evaluation and tracking.
141
+ - `src/softasp/instantiations/`: configuration-driven dispatch and Sudoku providers.
142
+ - `configs/instantiation/sudoku.yaml`: the bundled instantiation's composition.
143
+ - Sudoku-named modules contain its data generation, constraints and task-specific behavior.
144
+
145
+ ## Results and limits
146
+
147
+ The included model achieved **955/1,000 fully solved test boards (95.5%)**,
148
+ **80,905/81,000 correct cells (99.8827%)**, and **45,000/45,000 correct clues**.
149
+ The selected checkpoint was epoch 187, with 95.4% validation board accuracy.
150
+ These are single-seed results from the legacy generated Sudoku protocol, using
151
+ raw CUDA float32 evaluation. Training used bf16 and the default six-layer,
152
+ 256-dimensional model.
153
+
154
+ Generated boards are transformations of one base solution and use a merged
155
+ MNIST image pool; source-image separation across dataset splits is not
156
+ established. These results do not establish generalization to independent
157
+ handwriting sources, arbitrary Sudoku distributions, or photographed boards.
158
+ Independent operator/numerical validation and broader paper reproduction are
159
+ outside this release. Device and precision changes can change predictions.
160
+
161
+ A subsequent full from-scratch run of the refactored framework completed training,
162
+ checkpoint loading, prediction and evaluation, obtaining **944/1,000 boards (94.4%)**
163
+ on the same test set. The included selected weights were re-evaluated at **95.5%**
164
+ and remain unchanged. The 1.1 percentage-point difference is unresolved; its
165
+ investigation is deferred until after this release. Exact training-result
166
+ reproduction is not claimed.
167
+
168
+ ## License
169
+
170
+ Project code and model weights are under **CC BY-NC 4.0**; see LICENSE.
171
+ Dependencies and MNIST source imagery retain their respective third-party
172
+ terms. The small example uses MNIST digit imagery and is not a newly licensed
173
+ dataset. See THIRD_PARTY_NOTICES.md. The release includes no full datasets.
THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party material
2
+
3
+ MNIST digit imagery is sourced from the MNIST database by Yann LeCun,
4
+ Corinna Cortes, and Christopher J. C. Burges. Training downloads it through
5
+ torchvision's MNIST dataset implementation. The small example board uses this
6
+ imagery; original dataset rights and terms remain applicable.
7
+
8
+ Project CC BY-NC 4.0 licensing does not replace the licenses of PyTorch,
9
+ torchvision, NumPy, Hydra, OmegaConf, Aim, h5py, Clingo, or other dependencies.
10
+ Their distributions include their respective license notices.
configs/config.yaml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SoftASP — top-level Hydra configuration
2
+ #
3
+ # Override groups on the CLI:
4
+ # softasp-train instantiation=sudoku paths=local
5
+ #
6
+ defaults:
7
+ - instantiation: sudoku
8
+ - paths: local
9
+ - logging: default
10
+ - _self_
11
+
12
+ experiment_name: softasp
13
+
14
+ # Clean-up settings (used by softasp-cleanup)
15
+ cleanup:
16
+ apply: false
17
+ keep_best_n: 3
18
+
19
+ # Hydra output directory override
20
+ hydra:
21
+ run:
22
+ dir: ${paths.output_dir}/${instantiation.name}/${experiment_name}/${now:%Y-%m-%d_%H-%M-%S}
23
+ sweep:
24
+ dir: ${paths.output_dir}/${instantiation.name}/multirun/${now:%Y-%m-%d_%H-%M-%S}
configs/dataset/sudoku.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Sudoku dataset configuration
2
+ name: sudoku
3
+ num_classes: 9 # digits 1-9 (stored as 0-indexed: 0-8)
4
+ image_size: 252 # 9 cells × 28 pixels each
5
+ max_objects: 81 # 9×9 grid cells
6
+ splits:
7
+ - train
8
+ - val
9
+ - test
10
+ augmentations:
11
+ train: []
12
+ val: []
13
+ test: []
configs/evaluator/sudoku.yaml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluator configuration for Visual Sudoku
2
+ datasets:
3
+ - sudoku
4
+ metrics:
5
+ - accuracy
6
+ - board_accuracy
7
+ - constraint_sat_rate
8
+ batch_size_per_gpu: 32
9
+ num_workers: 4
configs/instantiation/sudoku.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ # Sudoku owns its data, model, constraints, metrics and workflow adapters.
3
+ defaults:
4
+ - /dataset: sudoku
5
+ - /preprocessing: sudoku
6
+ - /model: softasp_sudoku
7
+ - /trainer: sudoku_softasp
8
+ - /evaluator: sudoku
9
+ - /model@backbone.model: perception_only_sudoku
10
+ - /trainer@backbone.trainer: sudoku
11
+ - _self_
12
+
13
+ checkpoint: models/sudoku/as2.pt
14
+ input: examples/sudoku.npz
15
+ evaluator:
16
+ checkpoint: ${checkpoint}
17
+
18
+ instantiation:
19
+ name: sudoku
20
+ version: 1
21
+ constraints:
22
+ _target_: softasp_solver.sudoku.constraints.TPOperatorLoss
23
+ providers:
24
+ dataset:
25
+ _target_: softasp.instantiations.sudoku.DatasetProvider
26
+ model:
27
+ _target_: softasp.instantiations.sudoku.ModelProvider
28
+ metrics:
29
+ _target_: softasp.instantiations.sudoku.MetricsProvider
30
+ prediction:
31
+ _target_: softasp.instantiations.sudoku.PredictionProvider
32
+ evaluation:
33
+ _target_: softasp.instantiations.sudoku.EvaluationProvider
34
+ workflow:
35
+ _target_: softasp.instantiations.sudoku.WorkflowProvider
36
+
37
+ # The bundled instantiation owns its complete two-stage recipe.
38
+ release_profile: sudoku_release1
39
+ experiment_name: sudoku_from_scratch
40
+ data_artifact:
41
+ protocol_id: null
42
+ path: null
43
+ sha256: null
44
+
45
+ paths:
46
+ model_dir: ${oc.env:SOFTASP_MODEL_DIR,models}
47
+
48
+ pipeline:
49
+ name: ${now:%Y-%m-%d_%H-%M-%S}
50
+ run_dir: ${paths.output_dir}/sudoku/from_scratch/${pipeline.name}
51
+ model_dir: ${paths.model_dir}/sudoku/${pipeline.name}
52
+ data_mode: generate # generate or existing (explicit path + SHA256 required)
53
+ download: true # false uses already downloaded MNIST; never needs weights
54
+
55
+ model:
56
+ pretrained_from: null
57
+ trainer:
58
+ protocol: sudoku_seeded_updates_v1
59
+ seed: 42
60
+ distributed: "false"
61
+ compile: false
62
+ gradient_accumulation_steps: 1
63
+ resume_from: null
64
+ scheduler:
65
+ name: linear_warmup_cosine
66
+ warmup_steps: 200
67
+ eval_on_start: false
68
+ experiment_name: sudoku_from_scratch_as2
69
+ backbone:
70
+ model:
71
+ params:
72
+ d_model: ${oc.select:model.params.d_model,128}
73
+ trainer:
74
+ protocol: sudoku_seeded_updates_v1
75
+ seed: ${trainer.seed}
76
+ distributed: "false"
77
+ compile: false
78
+ gradient_accumulation_steps: 1
79
+ resume_from: null
80
+ eval_on_start: false
81
+ precision: ${trainer.precision}
82
+ scheduler:
83
+ name: linear_warmup_cosine
84
+ experiment_name: sudoku_from_scratch_backbone
85
+
configs/logging/default.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Logging configuration
2
+ level: INFO
3
+ rich_console: true
4
+ file_log: true
5
+ log_every_n_steps: 10
6
+ # Log board images to Aim every N eval epochs (0 = never)
7
+
8
+ log_images_every_n_epochs: 0
configs/model/perception_only_sudoku.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Perception-only baseline for Visual Sudoku (no reasoning)
2
+ name: perception_only_sudoku
3
+ pretrained_from: null
4
+ # PerceptionOnly IS the backbone pre-training run. It trains from scratch
5
+ # (no pretrained_from) so freeze_backbone_epochs is irrelevant here.
6
+ freeze_backbone_epochs: 0
7
+ # Aim tags — distinct from SoftASP so the two can be compared in one query.
8
+ tags:
9
+ - perception-only
10
+ - cnn-only
11
+ - sudoku
12
+ params:
13
+ d_model: 256
configs/model/softasp_sudoku.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: softasp_sudoku
2
+ pretrained_from: null
3
+ freeze_backbone_epochs: 20
4
+ tags:
5
+ - softasp
6
+ - ours
7
+ - sudoku
8
+ params:
9
+ d_model: 256
10
+ n_heads: 8
11
+ n_layers: 6
12
+ dropout: 0.1
13
+ lambda_ic: 5.0
14
+ lambda_blank: 0.3
15
+ blank_decay_epochs: 100
16
+ ic_warmup_epochs: 20
17
+ lambda_uniq: 0.0
18
+ backbone: default
19
+ oracle_perception: false
configs/paths/local.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ data_root: ${oc.env:SOFTASP_DATA_ROOT,data}
2
+ output_dir: ${oc.env:SOFTASP_OUTPUT_DIR,outputs}
3
+ aim_repo: ${paths.output_dir}/aim
4
+ raw_data_root: null
5
+ model_dir: ${oc.env:SOFTASP_MODEL_DIR,models}
configs/predict.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defaults:
2
+ - instantiation: sudoku
3
+ - paths: local
4
+ - _self_
5
+
6
+ output: outputs/prediction.json
7
+ device: auto
8
+ hydra:
9
+ run:
10
+ dir: outputs/hydra/predict/${now:%Y-%m-%d_%H-%M-%S}
11
+ job:
12
+ chdir: false
configs/preprocessing/sudoku.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Sudoku preprocessing
2
+ # Generation parameters are hardcoded in SudokuPreprocessor to avoid extra
3
+ # DatasetConfig fields. Current values:
4
+ # n_clues_start = 55 (start with 55 random clues — almost always unique)
5
+ # max_removals = 10 (remove up to 10 clues while preserving uniqueness)
6
+ # Result: ~45 clues per board, all uniquely solvable, no warnings.
7
+ # For publication: increase max_removals to get true minimal puzzles (~25–35 clues).
8
+ device: cpu
9
+ subset_size: null
10
+ chunk_size: 256
11
+ compression: gzip
12
+ compression_opts: 4
13
+ force: false
14
+ num_workers: 4
configs/sudoku_from_scratch.yaml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ defaults:
2
+ - train_scratch
3
+ - _self_
configs/sudoku_release1.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Supported Release 1 training surface. Supply an existing backbone explicitly.
2
+ # This configuration never launches backbone pretraining or extraction.
3
+ defaults:
4
+ - config
5
+ - override dataset: sudoku
6
+ - override preprocessing: sudoku
7
+ - override model: softasp_sudoku
8
+ - override trainer: sudoku_softasp
9
+ - override evaluator: sudoku
10
+ - _self_
11
+
12
+ release_profile: sudoku_release1
13
+ experiment_name: sudoku_release1
14
+ # Release 1 uses the existing verified legacy dataset; no regeneration required.
15
+ # Supply its location via this environment variable or a Hydra path override.
16
+ data_artifact:
17
+ protocol_id: sudoku_legacy_mnist_pool_v1
18
+ path: ${oc.env:SOFTASP_SUDOKU_HDF5,null}
19
+ sha256: 8d0070b00ffc75763ceb8c2b29006823c80b70f50b6ca0018310d0fdc7b3828e
20
+ evaluator:
21
+ checkpoint: models/sudoku/as2.pt
22
+ model:
23
+ pretrained_from: null
24
+ params:
25
+ oracle_perception: false
26
+ trainer:
27
+ protocol: sudoku_seeded_updates_v1
28
+ seed: 42
29
+ distributed: "false"
30
+ compile: false
31
+ gradient_accumulation_steps: 1
32
+ resume_from: null
33
+ experiment_name: sudoku_release1
34
+ scheduler:
35
+ name: linear_warmup_cosine
36
+ warmup_steps: 200
configs/train_scratch.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Each selected instantiation supplies its workflow recipe.
2
+ defaults:
3
+ - config
4
+ - _self_
5
+
6
+ hydra:
7
+ run:
8
+ dir: ${paths.output_dir}/hydra/train_scratch/${now:%Y-%m-%d_%H-%M-%S}
9
+ job:
10
+ chdir: false
configs/trainer/default.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Default trainer configuration
2
+ seed: 42
3
+ epochs: 10
4
+ batch_size_per_gpu: 64
5
+ lr: 0.0003
6
+ lr_scale_with_batch: false
7
+ weight_decay: 0.01
8
+ optimizer: adamw # adamw | adam | sgd
9
+ grad_clip_norm: 1.0
10
+ gradient_accumulation_steps: 1
11
+ precision: fp32 # fp32 | fp16 | bf16
12
+ compile: false
13
+ deterministic: false
14
+ strategy: ddp # ddp | fsdp
15
+ distributed: auto # auto | true | false
16
+ num_workers: 4
17
+ persistent_workers: true
18
+
19
+ # Scheduler
20
+ scheduler:
21
+ name: cosine
22
+ warmup_steps: 500
23
+ min_lr: 0.00001
24
+ step_size: 30
25
+ gamma: 0.1
26
+
27
+ # Evaluation
28
+ eval_every: 1
29
+ eval_split: val
30
+ eval_on_start: true
31
+
32
+ # Early stopping
33
+ early_stopping:
34
+ enabled: true
35
+ patience: 50
36
+ monitor: val_loss
37
+ mode: min
38
+
39
+ # Checkpointing
40
+ checkpoint_every: 1
41
+ monitor_metric: val_loss
42
+ monitor_mode: min
43
+ resume_from: null
44
+
45
+ # Experiment
46
+ experiment_name: default
47
+ tags: []
configs/trainer/sudoku.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ seed: 42
2
+ epochs: 200
3
+ batch_size_per_gpu: 32
4
+ lr: 0.0003
5
+ lr_scale_with_batch: false
6
+ weight_decay: 0.01
7
+ optimizer: adamw
8
+ grad_clip_norm: 1.0
9
+ gradient_accumulation_steps: 1
10
+ precision: fp32
11
+ compile: false
12
+ deterministic: false
13
+ strategy: ddp
14
+ distributed: "false"
15
+ num_workers: 4
16
+ persistent_workers: true
17
+
18
+ scheduler:
19
+ name: linear_warmup_cosine
20
+ warmup_steps: 200
21
+ min_lr: 0.00001
22
+ step_size: 60
23
+ gamma: 0.1
24
+
25
+ eval_every: 1
26
+ eval_split: val
27
+ eval_on_start: false
28
+
29
+ early_stopping:
30
+ enabled: true
31
+ patience: 50
32
+ monitor: clue_accuracy
33
+ mode: max
34
+
35
+ checkpoint_every: 1
36
+ monitor_metric: clue_accuracy
37
+ monitor_mode: max
38
+ resume_from: null
39
+
40
+ experiment_name: softasp_pretrain_backbone
41
+ tags:
42
+ - sudoku
43
+ - perception
44
+ - baseline
45
+ - prelim
configs/trainer/sudoku_softasp.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ protocol: sudoku_seeded_updates_v1
2
+ seed: 42
3
+ epochs: 200
4
+ batch_size_per_gpu: 32
5
+ lr: 0.0003
6
+ lr_scale_with_batch: false
7
+ weight_decay: 0.01
8
+ optimizer: adamw
9
+ grad_clip_norm: 1.0
10
+ gradient_accumulation_steps: 1
11
+ precision: fp32
12
+ compile: false
13
+ deterministic: false
14
+ strategy: ddp
15
+ distributed: "false"
16
+ num_workers: 4
17
+ persistent_workers: true
18
+
19
+ scheduler:
20
+ name: linear_warmup_cosine
21
+ warmup_steps: 200
22
+ min_lr: 0.00001
23
+ step_size: 60
24
+ gamma: 0.1
25
+
26
+ eval_every: 1
27
+ eval_split: val
28
+ eval_on_start: false
29
+
30
+ early_stopping:
31
+ enabled: true
32
+ patience: 50
33
+ monitor: constraint_sat_rate
34
+ mode: max
35
+
36
+ checkpoint_every: 1
37
+ monitor_metric: constraint_sat_rate
38
+ monitor_mode: max
39
+ resume_from: null
40
+
41
+ experiment_name: softasp_sudoku
42
+ tags:
43
+ - sudoku
44
+ - softasp
45
+ - ours
46
+ - prelim
docs/instantiations.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adding an AS² instantiation
2
+
3
+ An instantiation is a Hydra configuration plus the task-specific implementations
4
+ it selects. Visual Sudoku is the bundled example. MNIST Addition and CLEVR-Hans
5
+ are future targets, not runnable options in this release.
6
+
7
+ The shared commands dispatch by capability, with no benchmark branches:
8
+
9
+ ```bash
10
+ uv run --locked softasp-train instantiation=your_task
11
+ uv run --locked softasp-train-scratch instantiation=your_task
12
+ uv run --locked softasp-predict instantiation=your_task
13
+ uv run --locked softasp-evaluate instantiation=your_task
14
+ ```
15
+
16
+ These commands require your implementation and configuration to exist. Place
17
+ `your_task.yaml` in `configs/instantiation/`, or supply an additional Hydra config
18
+ search directory containing that group. Install your provider module in the same
19
+ uv environment. No shared CLI or framework source edits are needed to select an
20
+ implemented instantiation.
21
+
22
+ ## Configuration contract
23
+
24
+ Use `# @package _global_` so the instantiation can compose dataset, preprocessing,
25
+ model, trainer, evaluator, paths and any workflow-specific sections. The bundled
26
+ [`sudoku.yaml`](../configs/instantiation/sudoku.yaml) is a complete working example.
27
+
28
+ An extension configuration follows this structure (provider names are illustrative):
29
+
30
+ ```yaml
31
+ # @package _global_
32
+ defaults:
33
+ - /trainer: default
34
+ - _self_
35
+
36
+ dataset:
37
+ name: your_task
38
+ # Dataset parameters, splits, paths and preprocessing choices go here.
39
+ model:
40
+ name: your_model
41
+ pretrained_from: null
42
+ freeze_backbone_epochs: 0
43
+ params: {}
44
+ evaluator:
45
+ checkpoint: null
46
+ metrics: [accuracy]
47
+
48
+ instantiation:
49
+ name: your_task
50
+ version: 1
51
+ constraints:
52
+ _target_: your_package.constraints.ConstraintLoss
53
+ providers:
54
+ dataset: {_target_: your_package.providers.DatasetProvider}
55
+ model: {_target_: your_package.providers.ModelProvider}
56
+ metrics: {_target_: your_package.providers.MetricsProvider}
57
+ prediction: {_target_: your_package.providers.PredictionProvider}
58
+ evaluation: {_target_: your_package.providers.EvaluationProvider}
59
+ workflow: {_target_: your_package.providers.WorkflowProvider}
60
+ ```
61
+
62
+ Add hyperparameters, data identities, paths, network composition, objective
63
+ weights, evidence policies, input/output settings and workflow stages needed by
64
+ your task. Use the existing trainer schema and configuration groups; unknown
65
+ trainer fields are not arbitrary model parameters. Model-specific settings belong
66
+ under `model.params` or an instantiation-owned section. The top-level `paths`
67
+ group is composed by the common training configurations; prediction configurations
68
+ also compose it explicitly. `predict` supplies `checkpoint`, `input`, `output`
69
+ and `device` for the bundled adapter; another adapter may define different inputs.
70
+
71
+ ## Provider methods
72
+
73
+ Hydra constructs each provider from its `_target_` and constructor parameters.
74
+ Keep provider construction free of stochastic model initialization; build models
75
+ inside `prepare` or `build`, after the training entrypoint applies its seed policy.
76
+
77
+ | Provider | Required methods | Contract |
78
+ |---|---|---|
79
+ | Dataset | `build(cfg)` | Return `(training_dataset, validation_dataset)`; handle task-specific preparation/selection and identity validation. |
80
+ | Model | `prepare(cfg)`, `build(cfg)` | `prepare` returns a model or `None` before dataset construction; `build` constructs after datasets if needed. Bind configured constraints/objectives here. |
81
+ | Model inference | `load(cfg)` | Required by `softasp.inference.load_model(cfg)`; validate and strictly load the selected checkpoint. |
82
+ | Metrics | `build(cfg)` | Return an evaluator with `evaluate(model, loader, device) -> dict[str, float]`. |
83
+ | Prediction | `run(cfg)` | Return a JSON-serializable result. The common CLI writes `cfg.output` without overwriting an existing file. Never use solution labels. |
84
+ | Evaluation | `run(cfg)` | Score configured splits and write task-specific reports/provenance; return a result dictionary. |
85
+ | Workflow | `run(cfg)` | Execute the task's full workflow and return its result/artifact path. It may call shared `run_training(cfg)`. |
86
+
87
+ Training datasets yield dictionaries of tensors accepted by the shared loader.
88
+ Models implement `BaseSoftASPModel.forward(batch)` with a differentiable `loss`
89
+ and appropriate logits or predictions. The standard evaluator uses `labels` and
90
+ `logits`/`predictions`; supply a custom evaluator for other target/output contracts.
91
+ For freezing or gradient ramps, expose the relevant module through
92
+ `get_backbone()`. A model without a backbone returns `None`.
93
+
94
+ ## Reusable components and task-specific constraints
95
+
96
+ `softasp_solver.components.reasoning.AS2Network` composes an encoder, concept head,
97
+ probability projection, attention module, task head and optional structure module.
98
+ Its input encoder produces `(batch, positions, features)`. A task head may return
99
+ per-position outputs or pool into a classification output. Images, 81 positions,
100
+ nine symbols, Sudoku masks and per-cell predictions are not framework requirements.
101
+
102
+ The `components` package also supplies explicit evidence policies and structural
103
+ embeddings; `constraints` supplies shared operators and fixed-point residuals.
104
+ An instantiation may reuse these components or provide another differentiable
105
+ implementation appropriate to its declarative constraints.
106
+
107
+ Each instantiation owns its constraint specification and implementation. Sudoku
108
+ keeps both in `softasp_solver.sudoku.constraints`, with its training objectives
109
+ in `softasp_solver.sudoku.objective`. Changing specification text alone does not
110
+ change the numerical implementation: there is no automatic ASP compiler.
111
+
112
+ ## Checkpoints and verification
113
+
114
+ Training saves the resolved configuration, including instantiation identity and
115
+ providers. The common resume path validates instantiation/model identity and
116
+ constraint/network configuration before restoring state. Prediction/evaluation
117
+ providers must call the shared checkpoint validation helpers and load state
118
+ strictly; the bundled Sudoku providers do so. Only the explicitly recognized
119
+ legacy Sudoku inference checkpoint is accepted without instantiation metadata.
120
+
121
+ Test your adapter through all four commands, checkpoint round-trip, incompatible
122
+ identity rejection, and label-free prediction. The release's development checks
123
+ exercise a non-image, pooled-head AS² fixture with its own constraint residual
124
+ through the same entrypoints. That fixture is an interface test, not an additional
125
+ scientific benchmark. Dataset downloading and from-scratch stage order belong
126
+ to the instantiation; the common framework does not impose Sudoku's two-stage recipe.
examples/sudoku.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56834dcc68137cc20e753a969a7f70e10c7ca59559129e8a25fba0f3cf54682b
3
+ size 8772
models/sudoku/as2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3dd9bc93a91a9421bec01e07fde3ddad69d996b7a33eaa8d86bed588d239ed8
3
+ size 19549571
models/sudoku/metadata.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "pytorch-state-dict",
3
+ "checkpoint": "as2.pt",
4
+ "sha256": "d3dd9bc93a91a9421bec01e07fde3ddad69d996b7a33eaa8d86bed588d239ed8",
5
+ "source_revision": "7a50cf280201aed800837ae327cb1c47fbb3fbc2",
6
+ "seed": 42,
7
+ "selected_epoch": 187,
8
+ "test_board_accuracy": 0.955,
9
+ "test_boards": 1000,
10
+ "decoder": "raw_argmax",
11
+ "training_precision": "bf16",
12
+ "evaluation_precision": "float32",
13
+ "data_protocol": "sudoku_legacy_mnist_pool_v1"
14
+ }
models/sudoku/model.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "softasp_sudoku",
3
+ "pretrained_from": null,
4
+ "freeze_backbone_epochs": 20,
5
+ "tags": [
6
+ "softasp",
7
+ "ours",
8
+ "sudoku"
9
+ ],
10
+ "params": {
11
+ "d_model": 256,
12
+ "n_heads": 8,
13
+ "n_layers": 6,
14
+ "dropout": 0.1,
15
+ "lambda_ic": 5.0,
16
+ "lambda_blank": 0.3,
17
+ "blank_decay_epochs": 100,
18
+ "ic_warmup_epochs": 20,
19
+ "lambda_uniq": 0.0,
20
+ "backbone": "default",
21
+ "oracle_perception": false
22
+ }
23
+ }
packages/softasp-core/LICENSE ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution-NonCommercial 4.0 International
2
+
3
+ Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
4
+
5
+ Using Creative Commons Public Licenses
6
+
7
+ Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
8
+
9
+ Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
10
+
11
+ Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
12
+
13
+ Creative Commons Attribution-NonCommercial 4.0 International Public License
14
+
15
+ By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
16
+
17
+ Section 1 – Definitions.
18
+
19
+ a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
20
+
21
+ b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
22
+
23
+ c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
24
+
25
+ d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
26
+
27
+ e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
28
+
29
+ f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
30
+
31
+ g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
32
+
33
+ h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
34
+
35
+ i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
36
+
37
+ j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
38
+
39
+ k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
40
+
41
+ l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
42
+
43
+ Section 2 – Scope.
44
+
45
+ a. License grant.
46
+
47
+ 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
48
+
49
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
50
+
51
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
52
+
53
+ 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
54
+
55
+ 3. Term. The term of this Public License is specified in Section 6(a).
56
+
57
+ 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
58
+
59
+ 5. Downstream recipients.
60
+
61
+ A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
62
+
63
+ B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
64
+
65
+ 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
66
+
67
+ b. Other rights.
68
+
69
+ 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
70
+
71
+ 2. Patent and trademark rights are not licensed under this Public License.
72
+
73
+ 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
74
+
75
+ Section 3 – License Conditions.
76
+
77
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
78
+
79
+ a. Attribution.
80
+
81
+ 1. If You Share the Licensed Material (including in modified form), You must:
82
+
83
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
84
+
85
+ i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
86
+
87
+ ii. a copyright notice;
88
+
89
+ iii. a notice that refers to this Public License;
90
+
91
+ iv. a notice that refers to the disclaimer of warranties;
92
+
93
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
94
+
95
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
96
+
97
+ C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
98
+
99
+ 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
100
+
101
+ 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
102
+
103
+ 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
104
+
105
+ Section 4 – Sui Generis Database Rights.
106
+
107
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
108
+
109
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
110
+
111
+ b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
112
+
113
+ c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
114
+ For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
115
+
116
+ Section 5 – Disclaimer of Warranties and Limitation of Liability.
117
+
118
+ a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
119
+
120
+ b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
121
+
122
+ c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
123
+
124
+ Section 6 – Term and Termination.
125
+
126
+ a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
127
+
128
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
129
+
130
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
131
+
132
+ 2. upon express reinstatement by the Licensor.
133
+
134
+ For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
135
+
136
+ c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
137
+
138
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
139
+
140
+ Section 7 – Other Terms and Conditions.
141
+
142
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
143
+
144
+ b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
145
+
146
+ Section 8 – Interpretation.
147
+
148
+ a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
149
+
150
+ b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
151
+
152
+ c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
153
+
154
+ d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
155
+
156
+ Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
157
+
158
+ Creative Commons may be contacted at creativecommons.org.
packages/softasp-core/pyproject.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "softasp-core"
3
+ version = "0.1.0"
4
+ description = "SoftASP core infrastructure: config, data, training, evaluation, tracking"
5
+ requires-python = ">=3.12"
6
+ license = "CC-BY-NC-4.0"
7
+ license-files = ["LICENSE"]
8
+ dependencies = [
9
+ "torch>=2.2",
10
+ "requests>=2.31",
11
+ "h5py>=3.10",
12
+ "numpy>=1.26",
13
+ "aim>=3.19",
14
+ "omegaconf>=2.3",
15
+ "hydra-core>=1.3",
16
+ "rich>=13.0",
17
+ ]
18
+
19
+ [build-system]
20
+ requires = ["hatchling"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/softasp_core"]
packages/softasp-core/src/softasp_core/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """SoftASP core infrastructure: config, data, training, evaluation, tracking."""
2
+
3
+ __version__ = "0.1.0"
packages/softasp-core/src/softasp_core/config/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration schemas, validation, and loading."""
2
+
3
+ from softasp_core.config.loader import load_config
4
+ from softasp_core.config.schemas import (
5
+ DatasetConfig,
6
+ EarlyStoppingConfig,
7
+ EvaluatorConfig,
8
+ LoggingConfig,
9
+ ModelConfig,
10
+ PathsConfig,
11
+ PreprocessingConfig,
12
+ SchedulerConfig,
13
+ TrainerConfig,
14
+ )
15
+ from softasp_core.config.validation import validate_config
16
+
17
+ __all__ = [
18
+ "DatasetConfig",
19
+ "EarlyStoppingConfig",
20
+ "EvaluatorConfig",
21
+ "LoggingConfig",
22
+ "ModelConfig",
23
+ "PathsConfig",
24
+ "PreprocessingConfig",
25
+ "SchedulerConfig",
26
+ "TrainerConfig",
27
+ "load_config",
28
+ "validate_config",
29
+ ]
packages/softasp-core/src/softasp_core/config/loader.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load Hydra configs programmatically — works in scripts, notebooks, and tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from hydra import compose, initialize_config_dir
10
+ from omegaconf import DictConfig, OmegaConf
11
+
12
+
13
+ _CONFIGS_DIR = str(Path(__file__).resolve().parents[5] / "configs")
14
+
15
+
16
+ def load_config(
17
+ overrides: list[str] | None = None,
18
+ config_name: str = "config",
19
+ configs_dir: str | None = None,
20
+ ) -> DictConfig:
21
+ """Load and return a fully-resolved Hydra config.
22
+
23
+ Args:
24
+ overrides: Hydra-style overrides, e.g. ``["dataset=sudoku", "trainer.lr=1e-3"]``.
25
+ config_name: Name of the master config file (without .yaml).
26
+ configs_dir: Absolute path to the configs directory. Defaults to
27
+ ``<repo_root>/configs``.
28
+
29
+ Returns:
30
+ Fully resolved OmegaConf DictConfig.
31
+ """
32
+ configs_dir = configs_dir or os.environ.get("SOFTASP_CONFIGS_DIR", _CONFIGS_DIR)
33
+ overrides = overrides or []
34
+
35
+ with initialize_config_dir(config_dir=configs_dir, version_base="1.3"):
36
+ cfg = compose(config_name=config_name, overrides=overrides)
37
+
38
+ # Resolve all interpolations eagerly so downstream code sees plain values.
39
+ OmegaConf.resolve(cfg)
40
+ return cfg
41
+
42
+
43
+ def config_to_dict(cfg: DictConfig) -> dict[str, Any]:
44
+ """Convert OmegaConf DictConfig to a plain Python dict (for Aim params)."""
45
+ return OmegaConf.to_container(cfg, resolve=True, throw_on_missing=True) # type: ignore[return-value]
packages/softasp-core/src/softasp_core/config/schemas.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed dataclass schemas for all Hydra config groups.
2
+
3
+ Every field that appears in a YAML config file has a corresponding
4
+ dataclass field here, giving type safety and IDE autocomplete.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ # ── Paths ─────────────────────────────────────────────────────────────────────
13
+
14
+
15
+ @dataclass
16
+ class PathsConfig:
17
+ """Filesystem paths supplied through configuration."""
18
+
19
+ data_root: str = "${oc.env:SOFTASP_DATA_ROOT,data}"
20
+ output_dir: str = "outputs"
21
+ aim_repo: str = ".aim"
22
+
23
+
24
+ # ── Dataset ───────────────────────────────────────────────────────────────────
25
+
26
+
27
+ @dataclass
28
+ class DatasetConfig:
29
+ """Per-dataset config (resolved via configs/dataset/<name>.yaml)."""
30
+
31
+ name: str
32
+ num_classes: int | None = None
33
+ image_size: int | None = None
34
+ max_objects: int | None = None
35
+ splits: list[str] = field(default_factory=lambda: ["train", "val", "test"])
36
+ augmentations: dict[str, list[str]] = field(
37
+ default_factory=lambda: {"train": [], "val": [], "test": []}
38
+ )
39
+ augmentation_params: dict[str, dict[str, Any]] = field(default_factory=dict)
40
+ subset_size: int | None = None
41
+
42
+
43
+ # ── Preprocessing ─────────────────────────────────────────────────────────────
44
+
45
+
46
+ @dataclass
47
+ class PreprocessingConfig:
48
+ """Controls how raw data is transformed into HDF5."""
49
+
50
+ device: str = "cpu" # cpu | cuda
51
+ subset_size: int | None = None # None = full dataset
52
+ chunk_size: int = 256
53
+ compression: str = "gzip"
54
+ compression_opts: int = 4
55
+ force: bool = False
56
+ num_workers: int = 4
57
+
58
+
59
+ # ── Model ─────────────────────────────────────────────────────────────────────
60
+
61
+
62
+ @dataclass
63
+ class ModelConfig:
64
+ """Model architecture config."""
65
+
66
+ name: str
67
+ pretrained_from: str | None = None
68
+ freeze_backbone_epochs: int = 0 # Epochs to freeze get_backbone(); 0 disables freezing.
69
+ ramp_backbone_epochs: int = (
70
+ 0 # 0 = hard unfreeze; >0 = linearly ramp backbone LR to full over N epochs after unfreeze
71
+ )
72
+ params: dict[str, Any] = field(default_factory=dict)
73
+ tags: list[str] = field(default_factory=list)
74
+
75
+
76
+ # ── Scheduler ─────────────────────────────────────────────────────────────────
77
+
78
+
79
+ @dataclass
80
+ class SchedulerConfig:
81
+ """Learning rate scheduler config."""
82
+
83
+ name: str = "cosine" # cosine | step | linear_warmup_cosine | none
84
+ warmup_steps: int = 500
85
+ min_lr: float = 1e-6
86
+ step_size: int = 30
87
+ gamma: float = 0.1
88
+
89
+
90
+ # ── Early stopping ────────────────────────────────────────────────────────────
91
+
92
+
93
+ @dataclass
94
+ class EarlyStoppingConfig:
95
+ """Early stopping config."""
96
+
97
+ enabled: bool = True
98
+ patience: int = 10
99
+ monitor: str = "val_loss"
100
+ mode: str = "min" # min | max
101
+
102
+
103
+ # ── Trainer ───────────────────────────────────────────────────────────────────
104
+
105
+
106
+ @dataclass
107
+ class TrainerConfig:
108
+ """Full trainer config — the single source of truth for training."""
109
+
110
+ protocol: str = "legacy_v0"
111
+ seed: int = 42
112
+ epochs: int = 100
113
+ batch_size_per_gpu: int = 16
114
+ lr: float = 1e-4
115
+ lr_scale_with_batch: bool = False
116
+ weight_decay: float = 1e-5
117
+ optimizer: str = "adamw" # adamw | adam | sgd
118
+ grad_clip_norm: float | None = 1.0
119
+ gradient_accumulation_steps: int = 1
120
+ precision: str = "fp32" # fp32 | fp16 | bf16
121
+ compile: bool = False
122
+ deterministic: bool = False
123
+ strategy: str = "ddp" # ddp | fsdp
124
+ distributed: str = "auto" # auto | true | false
125
+ num_workers: int = 4
126
+ persistent_workers: bool = True
127
+ scheduler: SchedulerConfig = field(default_factory=SchedulerConfig)
128
+ eval_every: int = 1
129
+ eval_split: str = "val"
130
+ eval_on_start: bool = True
131
+ checkpoint_every: int = 1
132
+ monitor_metric: str = "val_loss"
133
+ monitor_mode: str = "min" # min | max
134
+ resume_from: str | None = None
135
+ early_stopping: EarlyStoppingConfig = field(default_factory=EarlyStoppingConfig)
136
+ experiment_name: str = "default"
137
+ tags: list[str] = field(default_factory=list)
138
+
139
+
140
+ # ── Evaluator ─────────────────────────────────────────────────────────────────
141
+
142
+
143
+ @dataclass
144
+ class EvaluatorConfig:
145
+ """Evaluation harness config — datasets is a list, not inherited from trainer."""
146
+
147
+ datasets: list[str] = field(default_factory=list)
148
+ metrics: list[str] = field(default_factory=lambda: ["accuracy"])
149
+ batch_size_per_gpu: int = 32
150
+ num_workers: int = 4
151
+ threshold: float = 0.5
152
+ checkpoint: str | None = None
153
+
154
+
155
+ # ── Logging ───────────────────────────────────────────────────────────────────
156
+
157
+
158
+ @dataclass
159
+ class LoggingConfig:
160
+ """Logging config — overrides Hydra's default logging hijack."""
161
+
162
+ level: str = "INFO"
163
+ rich_console: bool = True
164
+ file_log: bool = True
165
+ log_every_n_steps: int = 10
packages/softasp-core/src/softasp_core/config/validation.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Config validation — catch bad combos before wasting GPU hours."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+ from typing import Any
8
+
9
+ import torch
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class ConfigValidationError(Exception):
15
+ """Raised when config contains incompatible settings."""
16
+
17
+
18
+ def validate_config(cfg: Any) -> None:
19
+ """Validate the full resolved config. Raises ConfigValidationError on problems."""
20
+
21
+ errors: list[str] = []
22
+ warnings: list[str] = []
23
+ trainer = cfg.trainer
24
+
25
+ # ── Precision checks ──────────────────────────────────────────────────
26
+ device_type = _detect_device_type()
27
+
28
+ if trainer.precision == "bf16" and device_type == "cpu":
29
+ errors.append("bf16 precision is not supported on CPU. Use fp32 or switch to GPU.")
30
+
31
+ if trainer.precision == "fp16" and device_type == "mps":
32
+ errors.append("fp16 (GradScaler) is not supported on MPS. Use bf16 or fp32.")
33
+
34
+ # ── DataLoader vs MPS ─────────────────────────────────────────────────
35
+ if device_type == "mps" and trainer.num_workers > 0:
36
+ warnings.append(
37
+ f"num_workers={trainer.num_workers} on MPS can hang. "
38
+ "Forcing num_workers=0."
39
+ )
40
+ trainer.num_workers = 0
41
+ trainer.persistent_workers = False
42
+
43
+ # ── DDP sanity ────────────────────────────────────────────────────────
44
+ gpu_count = torch.cuda.device_count() if torch.cuda.is_available() else 0
45
+ wants_distributed = trainer.distributed == "true" or (
46
+ trainer.distributed == "auto" and gpu_count > 1
47
+ )
48
+ if wants_distributed and gpu_count < 2:
49
+ warnings.append(
50
+ f"distributed={trainer.distributed} but only {gpu_count} GPU(s) found. "
51
+ "Running single-process."
52
+ )
53
+
54
+ # ── Gradient accumulation ─────────────────────────────────────────────
55
+ if trainer.gradient_accumulation_steps < 1:
56
+ errors.append("gradient_accumulation_steps must be >= 1.")
57
+
58
+ # ── Scheduler ─────────────────────────────────────────────────────────
59
+ valid_schedulers = {"cosine", "step", "linear_warmup_cosine", "none"}
60
+ if trainer.scheduler.name not in valid_schedulers:
61
+ errors.append(
62
+ f"Unknown scheduler '{trainer.scheduler.name}'. "
63
+ f"Valid: {valid_schedulers}"
64
+ )
65
+
66
+ # ── Early stopping mode ───────────────────────────────────────────────
67
+ if trainer.early_stopping.mode not in ("min", "max"):
68
+ errors.append(f"early_stopping.mode must be 'min' or 'max', got '{trainer.early_stopping.mode}'")
69
+
70
+ # ── Log computed values ───────────────────────────────────────────────
71
+ world_size = max(gpu_count, 1) if wants_distributed else 1
72
+ effective_batch = (
73
+ trainer.batch_size_per_gpu * world_size * trainer.gradient_accumulation_steps
74
+ )
75
+ logger.info(
76
+ "Effective batch size: %d (per_gpu=%d × world=%d × accum=%d)",
77
+ effective_batch,
78
+ trainer.batch_size_per_gpu,
79
+ world_size,
80
+ trainer.gradient_accumulation_steps,
81
+ )
82
+
83
+ # ── Emit ──────────────────────────────────────────────────────────────
84
+ for w in warnings:
85
+ logger.warning("CONFIG WARNING: %s", w)
86
+
87
+ if errors:
88
+ for e in errors:
89
+ logger.error("CONFIG ERROR: %s", e)
90
+ raise ConfigValidationError(
91
+ f"{len(errors)} config validation error(s):\n" + "\n".join(f" • {e}" for e in errors)
92
+ )
93
+
94
+ logger.info("Config validation passed.")
95
+
96
+
97
+ def _detect_device_type() -> str:
98
+ """Best-effort device type for validation (not authoritative for training)."""
99
+ if torch.cuda.is_available():
100
+ return "cuda"
101
+ if sys.platform == "darwin" and hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
102
+ return "mps"
103
+ return "cpu"
packages/softasp-core/src/softasp_core/data/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Data pipeline: downloaders, preprocessors, datasets, collation."""
2
+
3
+ from softasp_core.data.augmentations import AUGMENTATION_REGISTRY, get_augmentation
4
+ from softasp_core.data.base_downloader import BaseDownloader
5
+ from softasp_core.data.base_preprocessor import BasePreprocessor
6
+ from softasp_core.data.collate import masked_collate_fn
7
+ from softasp_core.data.hdf5_dataset import HDF5Dataset
8
+
9
+ __all__ = [
10
+ "AUGMENTATION_REGISTRY",
11
+ "BaseDownloader",
12
+ "BasePreprocessor",
13
+ "HDF5Dataset",
14
+ "get_augmentation",
15
+ "masked_collate_fn",
16
+ ]
packages/softasp-core/src/softasp_core/data/augmentations.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Augmentation registry — stochastic transforms applied on-the-fly.
2
+
3
+ Deterministic transforms (resize, normalize) are baked into HDF5.
4
+ Only stochastic augmentations live here.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+ import torch
13
+
14
+ # Type alias for augmentation callables
15
+ AugmentationFn = Callable[[torch.Tensor], torch.Tensor]
16
+
17
+ # ── Registry ──────────────────────────────────────────────────────────────────
18
+
19
+ AUGMENTATION_REGISTRY: dict[str, type] = {}
20
+
21
+
22
+ def register_augmentation(name: str):
23
+ """Decorator to register an augmentation class."""
24
+
25
+ def decorator(cls):
26
+ AUGMENTATION_REGISTRY[name] = cls
27
+ return cls
28
+
29
+ return decorator
30
+
31
+
32
+ def get_augmentation(name: str, **kwargs: Any) -> AugmentationFn:
33
+ """Instantiate a registered augmentation by name."""
34
+ if name not in AUGMENTATION_REGISTRY:
35
+ raise ValueError(
36
+ f"Unknown augmentation '{name}'. Available: {list(AUGMENTATION_REGISTRY.keys())}"
37
+ )
38
+ return AUGMENTATION_REGISTRY[name](**kwargs)
39
+
40
+
41
+ # ── Built-in augmentations ────────────────────────────────────────────────────
42
+
43
+
44
+ @register_augmentation("random_horizontal_flip")
45
+ class RandomHorizontalFlip:
46
+ """Randomly flip a CHW tensor horizontally."""
47
+
48
+ def __init__(self, p: float = 0.5) -> None:
49
+ self.p = p
50
+
51
+ def __call__(self, x: torch.Tensor) -> torch.Tensor:
52
+ if torch.rand(1).item() < self.p:
53
+ return x.flip(-1)
54
+ return x
55
+
56
+
57
+ @register_augmentation("random_crop")
58
+ class RandomCrop:
59
+ """Random crop with zero-padding for CHW tensors."""
60
+
61
+ def __init__(self, size: int = 224, padding: int = 4) -> None:
62
+ self.size = size
63
+ self.padding = padding
64
+
65
+ def __call__(self, x: torch.Tensor) -> torch.Tensor:
66
+ if self.padding > 0:
67
+ x = torch.nn.functional.pad(x, [self.padding] * 4, mode="constant", value=0)
68
+ _, h, w = x.shape
69
+ top = torch.randint(0, h - self.size + 1, (1,)).item()
70
+ left = torch.randint(0, w - self.size + 1, (1,)).item()
71
+ return x[:, top : top + self.size, left : left + self.size]
72
+
73
+
74
+ @register_augmentation("color_jitter")
75
+ class ColorJitter:
76
+ """Simple brightness/contrast jitter for CHW float tensors."""
77
+
78
+ def __init__(self, brightness: float = 0.2, contrast: float = 0.2) -> None:
79
+ self.brightness = brightness
80
+ self.contrast = contrast
81
+
82
+ def __call__(self, x: torch.Tensor) -> torch.Tensor:
83
+ b = 1.0 + (torch.rand(1).item() * 2 - 1) * self.brightness
84
+ c = 1.0 + (torch.rand(1).item() * 2 - 1) * self.contrast
85
+ mean = x.mean()
86
+ x = (x - mean) * c + mean
87
+ x = x * b
88
+ return x.clamp(0, 1)
89
+
90
+
91
+ @register_augmentation("hue_jitter")
92
+ class HueJitter:
93
+ """Random hue shift for (C, H, W) uint8 tensors.
94
+
95
+ Uses torchvision's adjust_hue which expects (3, H, W) uint8.
96
+ hue: max absolute hue shift in [0, 0.5] (fraction of full circle).
97
+ """
98
+
99
+ def __init__(self, hue: float = 0.2) -> None:
100
+ self.hue = hue
101
+
102
+ def __call__(self, x: torch.Tensor) -> torch.Tensor:
103
+ import torchvision.transforms.functional as TF
104
+
105
+ factor = (torch.rand(1).item() * 2 - 1) * self.hue
106
+ return TF.adjust_hue(x, factor)
packages/softasp-core/src/softasp_core/data/base_downloader.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract base class for dataset downloaders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import logging
7
+ from abc import ABC, abstractmethod
8
+ from pathlib import Path
9
+
10
+ import requests
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class BaseDownloader(ABC):
16
+ """Download raw data, verify SHA256 checksums, store in raw/<dataset>/."""
17
+
18
+ def __init__(self, raw_dir: Path) -> None:
19
+ self.raw_dir = raw_dir
20
+ self.raw_dir.mkdir(parents=True, exist_ok=True)
21
+
22
+ @abstractmethod
23
+ def download(self) -> None:
24
+ """Download all required files. Must be idempotent."""
25
+
26
+ @abstractmethod
27
+ def verify(self) -> bool:
28
+ """Return True if all expected files exist and checksums match."""
29
+
30
+ def run(self) -> None:
31
+ """Download if not already verified."""
32
+ if self.verify():
33
+ logger.info("Raw data already present and verified at %s", self.raw_dir)
34
+ return
35
+ logger.info("Downloading raw data to %s …", self.raw_dir)
36
+ self.download()
37
+ if not self.verify():
38
+ raise RuntimeError(f"Verification failed after download at {self.raw_dir}")
39
+ logger.info("Download complete and verified.")
40
+
41
+ # ── Helpers ───────────────────────────────────────────────────────────
42
+
43
+ @staticmethod
44
+ def download_file(url: str, dest: Path, expected_sha256: str | None = None) -> None:
45
+ """Stream-download *url* to *dest* with optional SHA256 verification."""
46
+ dest.parent.mkdir(parents=True, exist_ok=True)
47
+ if dest.exists() and expected_sha256:
48
+ if _sha256(dest) == expected_sha256:
49
+ logger.debug("File %s already exists with correct hash; skipping.", dest.name)
50
+ return
51
+
52
+ logger.info("Downloading %s → %s", url, dest)
53
+ resp = requests.get(url, stream=True, timeout=300)
54
+ resp.raise_for_status()
55
+ with open(dest, "wb") as f:
56
+ for chunk in resp.iter_content(chunk_size=1 << 20):
57
+ f.write(chunk)
58
+
59
+ if expected_sha256:
60
+ actual = _sha256(dest)
61
+ if actual != expected_sha256:
62
+ dest.unlink()
63
+ raise RuntimeError(
64
+ f"SHA256 mismatch for {dest.name}: "
65
+ f"expected {expected_sha256}, got {actual}"
66
+ )
67
+
68
+
69
+ def _sha256(path: Path) -> str:
70
+ h = hashlib.sha256()
71
+ with open(path, "rb") as f:
72
+ for chunk in iter(lambda: f.read(1 << 20), b""):
73
+ h.update(chunk)
74
+ return h.hexdigest()
packages/softasp-core/src/softasp_core/data/base_preprocessor.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract base class for dataset preprocessors.
2
+
3
+ Reads raw data → writes a versioned HDF5 file.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import logging
10
+ from abc import ABC, abstractmethod
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import h5py
16
+ import numpy as np
17
+
18
+ from softasp_core.utils.hashing import hash_config, hash_directory
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class BasePreprocessor(ABC):
24
+ """Transform raw data into a single versioned HDF5 file per dataset.
25
+
26
+ Subclasses implement :meth:`process_split` for each split.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ raw_dir: Path,
32
+ processed_dir: Path,
33
+ preprocessing_cfg: Any,
34
+ dataset_cfg: Any,
35
+ ) -> None:
36
+ self.raw_dir = raw_dir
37
+ self.processed_dir = processed_dir
38
+ self.preprocessing_cfg = preprocessing_cfg
39
+ self.dataset_cfg = dataset_cfg
40
+ self.processed_dir.mkdir(parents=True, exist_ok=True)
41
+
42
+ # ── Public interface ──────────────────────────────────────────────────
43
+
44
+ def run(self) -> Path:
45
+ """Preprocess raw → HDF5. Returns the HDF5 path."""
46
+ cfg_hash = hash_config(self.preprocessing_cfg)
47
+ raw_hash = hash_directory(self.raw_dir)
48
+ h5_path = self.processed_dir / f"v_{cfg_hash}.h5"
49
+ meta_path = self.processed_dir / f"v_{cfg_hash}.meta.json"
50
+
51
+ # Idempotent: skip if matching file exists
52
+ if h5_path.exists() and not getattr(self.preprocessing_cfg, "force", False):
53
+ if meta_path.exists():
54
+ meta = json.loads(meta_path.read_text())
55
+ if meta.get("raw_data_hash") == raw_hash:
56
+ logger.info("HDF5 already up to date: %s", h5_path)
57
+ return h5_path
58
+ logger.warning("Raw data changed — regenerating HDF5.")
59
+ else:
60
+ logger.info("HDF5 exists but no meta; regenerating.")
61
+
62
+ logger.info("Preprocessing → %s", h5_path)
63
+ samples_per_split: dict[str, int] = {}
64
+ stats: dict[str, Any] = {}
65
+
66
+ with h5py.File(h5_path, "w") as hf:
67
+ for split in self.dataset_cfg.splits:
68
+ logger.info(" Processing split: %s", split)
69
+ grp = hf.create_group(split)
70
+ n_samples = self.process_split(split, grp)
71
+ samples_per_split[split] = n_samples
72
+
73
+ # Store dataset-level stats if subclass provides them
74
+ stats = self.compute_stats(h5_path)
75
+
76
+ # Write sidecar metadata
77
+ meta_data = {
78
+ "preprocessing_config_hash": cfg_hash,
79
+ "raw_data_hash": raw_hash,
80
+ "created_at": datetime.now(timezone.utc).isoformat(),
81
+ "samples_per_split": samples_per_split,
82
+ "stats": stats,
83
+ }
84
+ meta_path.write_text(json.dumps(meta_data, indent=2))
85
+ logger.info("Preprocessing complete: %s (%s)", h5_path, samples_per_split)
86
+ return h5_path
87
+
88
+ # ── Abstract methods ──────────────────────────────────────────────────
89
+
90
+ @abstractmethod
91
+ def process_split(self, split: str, group: h5py.Group) -> int:
92
+ """Process a single split, write datasets into *group*.
93
+
94
+ Returns:
95
+ Number of samples written.
96
+ """
97
+
98
+ def compute_stats(self, h5_path: Path) -> dict[str, Any]:
99
+ """Optionally compute dataset statistics after all splits are written.
100
+
101
+ Returns:
102
+ Dict of stats (e.g. mean, std) to store in .meta.json.
103
+ """
104
+ return {}
105
+
106
+ # ── Helpers ───────────────────────────────────────────────────────────
107
+
108
+ @staticmethod
109
+ def create_chunked_dataset(
110
+ group: h5py.Group,
111
+ name: str,
112
+ shape: tuple[int, ...],
113
+ dtype: np.dtype | str = "float32",
114
+ compression: str | None = "gzip",
115
+ compression_opts: int = 4,
116
+ chunk_size: int = 256,
117
+ ) -> h5py.Dataset:
118
+ """Create an HDF5 dataset with chunking and optional compression."""
119
+ chunks = (min(chunk_size, shape[0]),) + shape[1:]
120
+ return group.create_dataset(
121
+ name,
122
+ shape=shape,
123
+ dtype=dtype,
124
+ chunks=chunks,
125
+ compression=compression,
126
+ compression_opts=compression_opts if compression else None,
127
+ )
128
+
129
+ @staticmethod
130
+ def create_label_dataset(
131
+ group: h5py.Group,
132
+ name: str,
133
+ data: np.ndarray,
134
+ ) -> h5py.Dataset:
135
+ """Create an uncompressed dataset for small arrays (labels, lengths)."""
136
+ return group.create_dataset(name, data=data)
packages/softasp-core/src/softasp_core/data/collate.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom collate function that produces masks for padded variable-length data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+
7
+
8
+ def masked_collate_fn(batch: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
9
+ """Collate a list of sample dicts into a batched dict.
10
+
11
+ For every field ``<name>_lengths`` in the sample, produces a boolean
12
+ mask ``<name>_mask`` of shape ``(B, max_len)`` where True indicates valid
13
+ positions.
14
+
15
+ Returns:
16
+ Dict with keys: each original field (stacked) plus generated masks.
17
+ """
18
+ if not batch:
19
+ return {}
20
+
21
+ keys = batch[0].keys()
22
+ collated: dict[str, torch.Tensor] = {}
23
+
24
+ for key in keys:
25
+ tensors = [sample[key] for sample in batch]
26
+ collated[key] = torch.stack(tensors, dim=0)
27
+
28
+ # Generate boolean masks from *_lengths fields
29
+ length_keys = [k for k in keys if k.endswith("_lengths")]
30
+ for lk in length_keys:
31
+ field_name = lk.removesuffix("_lengths")
32
+ lengths = collated[lk] # (B,)
33
+ max_len = int(lengths.max().item())
34
+ # True = valid position
35
+ mask = torch.arange(max_len, device=lengths.device).unsqueeze(0) < lengths.unsqueeze(1)
36
+ collated[f"{field_name}_mask"] = mask
37
+
38
+ return collated
packages/softasp-core/src/softasp_core/data/hdf5_dataset.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy-loading HDF5 dataset for PyTorch DataLoader.
2
+
3
+ Opens file handle once; reads individual samples in __getitem__.
4
+ Supports SWMR mode for concurrent multi-worker reads.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import h5py
14
+ import numpy as np
15
+ import torch
16
+ from torch.utils.data import Dataset
17
+
18
+ from softasp_core.data.augmentations import get_augmentation
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class HDF5Dataset(Dataset):
24
+ """A dataset backed by a single HDF5 file.
25
+
26
+ Args:
27
+ h5_path: Path to the HDF5 file.
28
+ split: Split group name (``train``, ``val``, ``test``).
29
+ fields: List of dataset names to read from the group.
30
+ Defaults to ``["images", "labels"]``.
31
+ augmentations: List of augmentation names to apply (from registry).
32
+ augmentation_params: Dict of augmentation name → params.
33
+ transform: Optional callable applied after augmentations.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ h5_path: str | Path,
39
+ split: str,
40
+ fields: list[str] | None = None,
41
+ augmentations: list[str] | None = None,
42
+ augmentation_params: dict[str, dict[str, Any]] | None = None,
43
+ transform: Any | None = None,
44
+ ) -> None:
45
+ self.h5_path = Path(h5_path)
46
+ self.split = split
47
+ self.fields = fields or ["images", "labels"]
48
+ self.transform = transform
49
+
50
+ # Build augmentation pipeline
51
+ self._augmentations = []
52
+ for aug_name in augmentations or []:
53
+ params = (augmentation_params or {}).get(aug_name, {})
54
+ self._augmentations.append(get_augmentation(aug_name, **params))
55
+
56
+ # Open file lazily — will be opened per-worker in DataLoader
57
+ self._h5_file: h5py.File | None = None
58
+ self._length: int = 0
59
+
60
+ # Read length eagerly (quick metadata read)
61
+ with h5py.File(self.h5_path, "r") as f:
62
+ first_field = self.fields[0]
63
+ self._length = f[self.split][first_field].shape[0]
64
+
65
+ def _open(self) -> h5py.File:
66
+ """Open (or reopen) the HDF5 file in SWMR mode."""
67
+ if self._h5_file is None:
68
+ self._h5_file = h5py.File(self.h5_path, "r", swmr=True)
69
+ return self._h5_file
70
+
71
+ def __len__(self) -> int:
72
+ return self._length
73
+
74
+ def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
75
+ f = self._open()
76
+ group = f[self.split]
77
+ sample: dict[str, torch.Tensor] = {}
78
+
79
+ for field in self.fields:
80
+ if field not in group:
81
+ continue
82
+ raw = group[field][idx]
83
+ tensor = torch.from_numpy(np.asarray(raw))
84
+
85
+ # Apply augmentations only to image-like fields
86
+ if field == "images":
87
+ for aug in self._augmentations:
88
+ tensor = aug(tensor)
89
+
90
+ sample[field] = tensor
91
+
92
+ # Read associated length/mask fields if they exist
93
+ for field in self.fields:
94
+ lengths_key = f"{field}_lengths"
95
+ if lengths_key in group:
96
+ sample[lengths_key] = torch.tensor(group[lengths_key][idx])
97
+
98
+ if self.transform is not None:
99
+ sample = self.transform(sample)
100
+
101
+ return sample
102
+
103
+ def __del__(self) -> None:
104
+ if self._h5_file is not None:
105
+ try:
106
+ self._h5_file.close()
107
+ except Exception:
108
+ pass
109
+
110
+ def __repr__(self) -> str:
111
+ return (
112
+ f"HDF5Dataset(path={self.h5_path.name}, split={self.split}, "
113
+ f"len={self._length}, fields={self.fields})"
114
+ )
packages/softasp-core/src/softasp_core/distributed/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distributed training utilities (DDP, FSDP)."""
2
+
3
+ from softasp_core.distributed.distributed import (
4
+ all_gather_predictions,
5
+ all_reduce_metrics,
6
+ cleanup_ddp,
7
+ get_device,
8
+ is_distributed,
9
+ is_main_process,
10
+ setup_ddp,
11
+ )
12
+ from softasp_core.distributed.eval_sampler import DistributedEvalSampler
13
+
14
+ __all__ = [
15
+ "DistributedEvalSampler",
16
+ "all_gather_predictions",
17
+ "all_reduce_metrics",
18
+ "cleanup_ddp",
19
+ "get_device",
20
+ "is_distributed",
21
+ "is_main_process",
22
+ "setup_ddp",
23
+ ]
packages/softasp-core/src/softasp_core/distributed/distributed.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DDP / FSDP setup and distributed helpers.
2
+
3
+ Uses ``torchrun`` environment variables (RANK, LOCAL_RANK, WORLD_SIZE).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import os
10
+ import sys
11
+ from typing import Any
12
+
13
+ import torch
14
+ import torch.distributed as dist
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ # ── Setup / teardown ──────────────────────────────────────────────────────────
20
+
21
+
22
+ def setup_ddp() -> None:
23
+ """Initialize the default process group from torchrun env vars."""
24
+ if not dist.is_available():
25
+ logger.warning("torch.distributed not available; skipping DDP init.")
26
+ return
27
+
28
+ rank = int(os.environ.get("RANK", 0))
29
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
30
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
31
+
32
+ if world_size <= 1:
33
+ return
34
+
35
+ backend = "nccl" if torch.cuda.is_available() else "gloo"
36
+ dist.init_process_group(backend=backend, rank=rank, world_size=world_size)
37
+ torch.cuda.set_device(local_rank)
38
+
39
+ logger.info(
40
+ "DDP initialized: rank=%d, local_rank=%d, world_size=%d, backend=%s",
41
+ rank,
42
+ local_rank,
43
+ world_size,
44
+ backend,
45
+ )
46
+
47
+
48
+ def cleanup_ddp() -> None:
49
+ """Destroy the process group if it was initialized."""
50
+ if dist.is_available() and dist.is_initialized():
51
+ dist.destroy_process_group()
52
+
53
+
54
+ # ── Queries ───────────────────────────────────────────────────────────────────
55
+
56
+
57
+ def is_distributed() -> bool:
58
+ return dist.is_available() and dist.is_initialized()
59
+
60
+
61
+ def is_main_process() -> bool:
62
+ """True on rank 0 or when not running distributed."""
63
+ if not is_distributed():
64
+ return True
65
+ return dist.get_rank() == 0
66
+
67
+
68
+ def get_rank() -> int:
69
+ if not is_distributed():
70
+ return 0
71
+ return dist.get_rank()
72
+
73
+
74
+ def get_world_size() -> int:
75
+ if not is_distributed():
76
+ return 1
77
+ return dist.get_world_size()
78
+
79
+
80
+ def get_device() -> torch.device:
81
+ """Determine the best available device.
82
+
83
+ Priority: CUDA (with LOCAL_RANK) > MPS > CPU.
84
+ """
85
+ if torch.cuda.is_available():
86
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
87
+ return torch.device(f"cuda:{local_rank}")
88
+
89
+ if (
90
+ sys.platform == "darwin"
91
+ and hasattr(torch.backends, "mps")
92
+ and torch.backends.mps.is_available()
93
+ ):
94
+ return torch.device("mps")
95
+
96
+ return torch.device("cpu")
97
+
98
+
99
+ # ── Communication helpers ─────────────────────────────────────────────────────
100
+
101
+
102
+ def all_reduce_metrics(metrics: dict[str, float]) -> dict[str, float]:
103
+ """Average scalar metrics across all ranks."""
104
+ if not is_distributed():
105
+ return metrics
106
+
107
+ reduced: dict[str, float] = {}
108
+ for key, value in metrics.items():
109
+ tensor = torch.tensor(value, dtype=torch.float64, device=get_device())
110
+ dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
111
+ reduced[key] = tensor.item() / get_world_size()
112
+ return reduced
113
+
114
+
115
+ def all_gather_predictions(
116
+ tensor: torch.Tensor,
117
+ ) -> torch.Tensor:
118
+ """Gather predictions from all ranks to rank 0.
119
+
120
+ Returns:
121
+ Concatenated tensor on all ranks (each rank gets the full result).
122
+ """
123
+ if not is_distributed():
124
+ return tensor
125
+
126
+ world_size = get_world_size()
127
+ gathered = [torch.zeros_like(tensor) for _ in range(world_size)]
128
+ dist.all_gather(gathered, tensor)
129
+ return torch.cat(gathered, dim=0)
packages/softasp-core/src/softasp_core/distributed/eval_sampler.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distributed eval sampler — pads so all ranks process equal counts.
2
+
3
+ Without this, DDP eval either drops samples (drop_last=True → wrong metrics)
4
+ or hangs (uneven batch counts across ranks → NCCL timeout).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ import torch
12
+ import torch.distributed as dist
13
+ from torch.utils.data import Dataset, Sampler
14
+
15
+
16
+ class DistributedEvalSampler(Sampler[int]):
17
+ """Sampler for evaluation under DDP.
18
+
19
+ - Pads indices so every rank processes the same count.
20
+ - After ``all_gather``, rank 0 must trim to ``len(dataset)`` before
21
+ computing metrics.
22
+
23
+ Args:
24
+ dataset: The dataset to sample from.
25
+ num_replicas: Number of processes (default: world_size).
26
+ rank: Current process rank.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ dataset: Dataset,
32
+ num_replicas: int | None = None,
33
+ rank: int | None = None,
34
+ ) -> None:
35
+ if num_replicas is None:
36
+ if dist.is_available() and dist.is_initialized():
37
+ num_replicas = dist.get_world_size()
38
+ else:
39
+ num_replicas = 1
40
+ if rank is None:
41
+ if dist.is_available() and dist.is_initialized():
42
+ rank = dist.get_rank()
43
+ else:
44
+ rank = 0
45
+
46
+ self.dataset = dataset
47
+ self.num_replicas = num_replicas
48
+ self.rank = rank
49
+ self.total_size = len(dataset) # type: ignore[arg-type]
50
+
51
+ # Pad to make evenly divisible
52
+ self.num_samples = math.ceil(self.total_size / self.num_replicas)
53
+ self.padded_size = self.num_samples * self.num_replicas
54
+
55
+ def __iter__(self):
56
+ indices = list(range(self.total_size))
57
+ # Pad by wrapping around
58
+ padding = self.padded_size - self.total_size
59
+ if padding > 0:
60
+ indices += indices[:padding]
61
+
62
+ # Subsample for this rank
63
+ offset = self.num_samples * self.rank
64
+ yield from indices[offset : offset + self.num_samples]
65
+
66
+ def __len__(self) -> int:
67
+ return self.num_samples
packages/softasp-core/src/softasp_core/evaluation/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation metrics and evaluation loop."""
2
+
3
+ from softasp_core.evaluation.evaluator import Evaluator
4
+ from softasp_core.evaluation.metrics import METRIC_REGISTRY, Accuracy, MetricProvider
5
+
6
+ __all__ = [
7
+ "METRIC_REGISTRY",
8
+ "Accuracy",
9
+ "Evaluator",
10
+ "MetricProvider",
11
+ ]
packages/softasp-core/src/softasp_core/evaluation/evaluator.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation loop — runs metrics across one or more datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch import autocast
10
+ from torch.utils.data import DataLoader
11
+
12
+ from softasp_core.evaluation.metrics import MetricProvider, get_metric
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class Evaluator:
18
+ """Run a model against a DataLoader and compute metrics.
19
+
20
+ Args:
21
+ metric_names: List of registered metric names to compute.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ metric_names: list[str] | None = None,
27
+ *,
28
+ output_metrics: dict[str, tuple[str, str]] | None = None,
29
+ scalar_keys: tuple[str, ...] = (),
30
+ ) -> None:
31
+ self.output_metrics = output_metrics or {}
32
+ self.scalar_keys = scalar_keys
33
+ self.metric_names = metric_names or ["accuracy"]
34
+ self._metrics: list[MetricProvider] = [get_metric(n) for n in self.metric_names]
35
+
36
+ def evaluate(
37
+ self,
38
+ model: nn.Module,
39
+ loader: DataLoader,
40
+ device: torch.device,
41
+ ) -> dict[str, float]:
42
+ """Compute configured metrics and optional output diagnostics."""
43
+ model.eval()
44
+ for m in self._metrics:
45
+ m.reset()
46
+
47
+ split_trackers: dict[str, MetricProvider] = {}
48
+ scalar_sums: dict[str, float] = {}
49
+ scalar_counts: dict[str, int] = {}
50
+
51
+ def _ensure_tracker(key: str) -> MetricProvider:
52
+ if key not in split_trackers:
53
+ m = get_metric("accuracy")
54
+ m.reset()
55
+ split_trackers[key] = m
56
+ return split_trackers[key]
57
+
58
+ with torch.no_grad():
59
+ for batch in loader:
60
+ batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
61
+ with autocast(device_type=device.type, enabled=False):
62
+ output = model(batch)
63
+
64
+ predictions = output.get("logits", output.get("predictions"))
65
+ targets = batch.get("labels")
66
+ if predictions is not None and targets is not None:
67
+ for m in self._metrics:
68
+ m.update(predictions, targets)
69
+
70
+ for name, (prediction_key, target_key) in self.output_metrics.items():
71
+ prediction = output.get(prediction_key)
72
+ target = output.get(target_key, batch.get(target_key))
73
+ if prediction is not None and target is not None:
74
+ _ensure_tracker(name).update(prediction, target)
75
+
76
+ # ── Scalar diagnostics ───────────────────────────────
77
+ for _sk in self.scalar_keys:
78
+ _sv = output.get(_sk)
79
+ if _sv is not None:
80
+ scalar_sums[_sk] = scalar_sums.get(_sk, 0.0) + float(_sv)
81
+ scalar_counts[_sk] = scalar_counts.get(_sk, 0) + 1
82
+ results: dict[str, float] = {}
83
+ for m in self._metrics:
84
+ results[m.name] = m.compute()
85
+
86
+ for tracker_name, tracker in split_trackers.items():
87
+ results[tracker_name] = tracker.compute()
88
+
89
+ for sk, sv in scalar_sums.items():
90
+ results[sk] = sv / scalar_counts[sk]
91
+
92
+ return results
packages/softasp-core/src/softasp_core/evaluation/metrics.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metric providers — abstract interface + built-in implementations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any
7
+
8
+ import torch
9
+
10
+ # ── Registry ──────────────────────────────────────────────────────────────────
11
+
12
+ METRIC_REGISTRY: dict[str, type["MetricProvider"]] = {}
13
+
14
+
15
+ def register_metric(name: str):
16
+ """Decorator to register a MetricProvider subclass."""
17
+ def decorator(cls):
18
+ METRIC_REGISTRY[name] = cls
19
+ return cls
20
+ return decorator
21
+
22
+
23
+ def get_metric(name: str, **kwargs: Any) -> "MetricProvider":
24
+ if name not in METRIC_REGISTRY:
25
+ raise ValueError(f"Unknown metric '{name}'. Available: {list(METRIC_REGISTRY.keys())}")
26
+ return METRIC_REGISTRY[name](**kwargs)
27
+
28
+
29
+ # ── Abstract base ─────────────────────────────────────────────────────────────
30
+
31
+
32
+ class MetricProvider(ABC):
33
+ """Accumulates predictions over batches, then computes a scalar metric."""
34
+
35
+ @abstractmethod
36
+ def reset(self) -> None:
37
+ """Clear accumulated state."""
38
+
39
+ @abstractmethod
40
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
41
+ """Accumulate one batch of predictions and targets."""
42
+
43
+ @abstractmethod
44
+ def compute(self) -> float:
45
+ """Compute and return the metric value."""
46
+
47
+ @property
48
+ @abstractmethod
49
+ def name(self) -> str:
50
+ """Human-readable metric name for logging."""
51
+
52
+
53
+ # ── Built-in metrics ─────────────────────────────────────────────────────────
54
+
55
+
56
+ @register_metric("accuracy")
57
+ class Accuracy(MetricProvider):
58
+ """Top-1 classification accuracy."""
59
+
60
+ def __init__(self) -> None:
61
+ self._correct = 0
62
+ self._total = 0
63
+
64
+ @property
65
+ def name(self) -> str:
66
+ return "accuracy"
67
+
68
+ def reset(self) -> None:
69
+ self._correct = 0
70
+ self._total = 0
71
+
72
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
73
+ if predictions.dim() > 1:
74
+ preds = predictions.argmax(dim=-1)
75
+ else:
76
+ preds = predictions
77
+ self._correct += (preds == targets).sum().item()
78
+ self._total += targets.numel()
79
+
80
+ def compute(self) -> float:
81
+ if self._total == 0:
82
+ return 0.0
83
+ return self._correct / self._total
84
+
85
+
86
+ @register_metric("auroc")
87
+ class AUROC(MetricProvider):
88
+ """Area Under ROC Curve (binary or macro-averaged multi-class).
89
+
90
+ Requires scikit-learn at compute time (lazy import).
91
+ """
92
+
93
+ def __init__(self) -> None:
94
+ self._scores: list[torch.Tensor] = []
95
+ self._targets: list[torch.Tensor] = []
96
+
97
+ @property
98
+ def name(self) -> str:
99
+ return "auroc"
100
+
101
+ def reset(self) -> None:
102
+ self._scores.clear()
103
+ self._targets.clear()
104
+
105
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
106
+ self._scores.append(predictions.detach().cpu())
107
+ self._targets.append(targets.detach().cpu())
108
+
109
+ def compute(self) -> float:
110
+ from sklearn.metrics import roc_auc_score
111
+
112
+ scores = torch.cat(self._scores).numpy()
113
+ targets = torch.cat(self._targets).numpy()
114
+ if scores.ndim > 1 and scores.shape[1] > 1:
115
+ return float(roc_auc_score(targets, scores, multi_class="ovr", average="macro"))
116
+ return float(roc_auc_score(targets, scores))
117
+
118
+
119
+ # ── CLEVR-POC metrics ────────────────────────────────────────────────────────
120
+
121
+
122
+ @register_metric("exact_accuracy")
123
+ class ExactAccuracy(MetricProvider):
124
+ """Exact set-match accuracy for CLEVR-POC multi-label prediction.
125
+
126
+ A prediction is correct only when the predicted attribute set matches the
127
+ ground-truth set exactly.
128
+
129
+ Args:
130
+ threshold: Probability threshold for binarising the 17-dim output.
131
+ """
132
+
133
+ def __init__(self, threshold: float = 0.5) -> None:
134
+ self.threshold = threshold
135
+ self._correct = 0
136
+ self._total = 0
137
+
138
+ @property
139
+ def name(self) -> str:
140
+ return "exact_accuracy"
141
+
142
+ def reset(self) -> None:
143
+ self._correct = 0
144
+ self._total = 0
145
+
146
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
147
+ """Accumulate one batch.
148
+
149
+ Args:
150
+ predictions: (B, 17) float — probabilities or logits.
151
+ targets: (B, 17) float — ground-truth multi-hot.
152
+ """
153
+ preds_bin = (predictions >= self.threshold).float()
154
+ exact = (preds_bin == targets.float()).all(dim=-1) # (B,)
155
+ self._correct += exact.sum().item()
156
+ self._total += targets.shape[0]
157
+
158
+ def compute(self) -> float:
159
+ if self._total == 0:
160
+ return 0.0
161
+ return self._correct / self._total
162
+
163
+
164
+ @register_metric("jaccard_index")
165
+ class JaccardIndex(MetricProvider):
166
+ """Mean Jaccard index (intersection over union) for CLEVR-POC.
167
+
168
+ Jaccard(A, P) = |A ∩ P| / |A ∪ P|
169
+
170
+ When both sets are empty the score for that example is defined as 1.0.
171
+
172
+ Args:
173
+ threshold: Probability threshold for binarising the 17-dim output.
174
+ """
175
+
176
+ def __init__(self, threshold: float = 0.5) -> None:
177
+ self.threshold = threshold
178
+ self._total_jaccard = 0.0
179
+ self._total = 0
180
+
181
+ @property
182
+ def name(self) -> str:
183
+ return "jaccard_index"
184
+
185
+ def reset(self) -> None:
186
+ self._total_jaccard = 0.0
187
+ self._total = 0
188
+
189
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
190
+ """Accumulate one batch.
191
+
192
+ Args:
193
+ predictions: (B, 17) float — probabilities or logits.
194
+ targets: (B, 17) float — ground-truth multi-hot.
195
+ """
196
+ preds_bin = (predictions >= self.threshold).float()
197
+ tgt = targets.float()
198
+ intersection = (preds_bin * tgt).sum(dim=-1) # (B,)
199
+ union = ((preds_bin + tgt).clamp(max=1.0)).sum(dim=-1) # (B,)
200
+ # Define 0/0 = 1.0 (perfect match when both are empty)
201
+ jaccard = torch.where(union > 0, intersection / union, torch.ones_like(union))
202
+ self._total_jaccard += jaccard.sum().item()
203
+ self._total += targets.shape[0]
204
+
205
+ def compute(self) -> float:
206
+ if self._total == 0:
207
+ return 0.0
208
+ return self._total_jaccard / self._total
209
+
210
+
211
+
212
+ @register_metric("board_accuracy")
213
+ class BoardAccuracy(MetricProvider):
214
+ """Whole-board accuracy for Sudoku: fraction of boards where ALL 81 cells
215
+ are correctly predicted.
216
+
217
+ Expects:
218
+ predictions: (B, 81, 9) logits or (B, 81) class indices.
219
+ targets: (B, 81) ground-truth 0-indexed digit labels.
220
+ """
221
+
222
+ def __init__(self) -> None:
223
+ self._correct = 0
224
+ self._total = 0
225
+
226
+ @property
227
+ def name(self) -> str:
228
+ return "board_accuracy"
229
+
230
+ def reset(self) -> None:
231
+ self._correct = 0
232
+ self._total = 0
233
+
234
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
235
+ if predictions.dim() == 3:
236
+ preds = predictions.argmax(dim=-1) # (B, 81)
237
+ else:
238
+ preds = predictions # already (B, 81)
239
+ # A board is correct iff every cell matches
240
+ board_correct = (preds == targets).all(dim=-1) # (B,)
241
+ self._correct += board_correct.sum().item()
242
+ self._total += targets.shape[0]
243
+
244
+ def compute(self) -> float:
245
+ if self._total == 0:
246
+ return 0.0
247
+ return self._correct / self._total
248
+
249
+
250
+ @register_metric("constraint_sat_rate")
251
+ class ConstraintSatRate(MetricProvider):
252
+ """Fraction of predicted boards that satisfy all Sudoku constraints
253
+ (each row, column, and 3×3 box contains digits 0-8 exactly once).
254
+
255
+ This metric does NOT require ground-truth labels — it only checks
256
+ structural validity of the predictions. It still accepts *targets*
257
+ in ``update()`` (ignored) to conform to the MetricProvider interface.
258
+
259
+ Expects:
260
+ predictions: (B, 81, 9) logits or (B, 81) class indices (0-8).
261
+ targets: ignored.
262
+ """
263
+
264
+ def __init__(self) -> None:
265
+ self._sat = 0
266
+ self._total = 0
267
+
268
+ @property
269
+ def name(self) -> str:
270
+ return "constraint_sat_rate"
271
+
272
+ def reset(self) -> None:
273
+ self._sat = 0
274
+ self._total = 0
275
+
276
+ def update(self, predictions: torch.Tensor, targets: torch.Tensor) -> None:
277
+ if predictions.dim() == 3:
278
+ preds = predictions.argmax(dim=-1) # (B, 81)
279
+ else:
280
+ preds = predictions
281
+ preds = preds.cpu()
282
+ B = preds.shape[0]
283
+ boards = preds.view(B, 9, 9) # (B, 9, 9)
284
+ full_set = set(range(9))
285
+ for b in range(B):
286
+ board = boards[b]
287
+ valid = True
288
+ # Check rows
289
+ for r in range(9):
290
+ if set(board[r].tolist()) != full_set:
291
+ valid = False
292
+ break
293
+ if not valid:
294
+ self._total += 1
295
+ continue
296
+ # Check columns
297
+ for c in range(9):
298
+ if set(board[:, c].tolist()) != full_set:
299
+ valid = False
300
+ break
301
+ if not valid:
302
+ self._total += 1
303
+ continue
304
+ # Check 3x3 boxes
305
+ for br in range(3):
306
+ for bc in range(3):
307
+ box = board[br * 3 : br * 3 + 3, bc * 3 : bc * 3 + 3]
308
+ if set(box.reshape(-1).tolist()) != full_set:
309
+ valid = False
310
+ break
311
+ if not valid:
312
+ break
313
+ if valid:
314
+ self._sat += 1
315
+ self._total += 1
316
+
317
+ def compute(self) -> float:
318
+ if self._total == 0:
319
+ return 0.0
320
+ return self._sat / self._total
packages/softasp-core/src/softasp_core/tracking/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Experiment tracking (Aim)."""
2
+
3
+ from softasp_core.tracking.aim_tracker import AimTracker
4
+
5
+ __all__ = ["AimTracker"]
packages/softasp-core/src/softasp_core/tracking/aim_tracker.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Aim experiment tracker — wraps the Aim SDK for DDP-safe logging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import subprocess
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def _ensure_aim_repo(repo_path: str) -> str:
15
+ """Ensure the Aim repo directory exists and is initialized.
16
+
17
+ Aim's ``Run(repo=path)`` expects *path* to be the directory that contains
18
+ the ``.aim`` subdirectory (i.e. the repo *root*), not the ``.aim``
19
+ directory itself. This helper accepts either convention, normalises to
20
+ the repo root, creates it if missing, and runs ``aim init`` if needed.
21
+
22
+ Returns the normalised repo-root path string.
23
+ """
24
+ p = Path(repo_path).resolve()
25
+ # If the caller passed ".../something/.aim", treat the parent as root.
26
+ if p.name == ".aim":
27
+ p = p.parent
28
+ p.mkdir(parents=True, exist_ok=True)
29
+ aim_dir = p / ".aim"
30
+ if not aim_dir.exists():
31
+ try:
32
+ subprocess.run(
33
+ ["aim", "init"],
34
+ cwd=str(p),
35
+ check=True,
36
+ capture_output=True,
37
+ )
38
+ logger.info("Aim repo initialised at %s", p)
39
+ except Exception as exc:
40
+ logger.warning("aim init failed (%s); will let Run() try anyway.", exc)
41
+ return str(p)
42
+
43
+
44
+ class AimTracker:
45
+ """Thin wrapper around Aim Run for DDP-safe experiment tracking.
46
+
47
+ Only rank 0 should instantiate this. All other ranks should skip tracking.
48
+
49
+ Args:
50
+ repo_path: Path to the Aim repo root (or its ``.aim`` subdirectory).
51
+ experiment_name: Experiment name for grouping.
52
+ run_hash: If resuming, the hash of the existing run.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ repo_path: str,
58
+ experiment_name: str = "default",
59
+ run_hash: str | None = None,
60
+ ) -> None:
61
+ # Aim's get_installed_packages() calls `import pkg_resources` which is
62
+ # only available when setuptools is installed. On lean venvs (Python
63
+ # 3.12+) it may be absent. Inject a no-op stub before Aim loads so
64
+ # the import path succeeds without requiring the full setuptools wheel.
65
+ import sys
66
+ if "pkg_resources" not in sys.modules:
67
+ import types
68
+ _stub = types.ModuleType("pkg_resources")
69
+ _stub.working_set = [] # type: ignore[attr-defined]
70
+ _stub.get_distribution = lambda _name: None # type: ignore[attr-defined]
71
+ sys.modules["pkg_resources"] = _stub
72
+
73
+ from aim import Run
74
+
75
+ repo_root = _ensure_aim_repo(repo_path)
76
+
77
+ self._run = Run(
78
+ repo=repo_root,
79
+ experiment=experiment_name,
80
+ run_hash=run_hash,
81
+ log_system_params=True,
82
+ )
83
+
84
+ # Tag with git commit if available
85
+ try:
86
+ commit = subprocess.check_output(
87
+ ["git", "rev-parse", "HEAD"], stderr=subprocess.DEVNULL
88
+ ).decode().strip()
89
+ self._run["git_commit"] = commit
90
+ except Exception:
91
+ pass
92
+
93
+ # Environment info
94
+ self._run["environment"] = os.environ.get("SOFTASP_ENV", "unknown")
95
+
96
+ logger.info("Aim run started: hash=%s, experiment=%s", self._run.hash, experiment_name)
97
+
98
+ @property
99
+ def run_hash(self) -> str:
100
+ return self._run.hash
101
+
102
+ def resume(self, run_hash: str) -> None:
103
+ """Reattach to an existing run (after checkpoint resume)."""
104
+ # Aim handles this automatically if run_hash is passed to __init__
105
+ logger.info("Aim run resumed: hash=%s", run_hash)
106
+
107
+ def log_params(self, params: dict[str, Any]) -> None:
108
+ """Log a flat dict of parameters."""
109
+ for key, value in params.items():
110
+ self._run[key] = value
111
+
112
+ def track(
113
+ self,
114
+ metrics: dict[str, float | int],
115
+ step: int | None = None,
116
+ epoch: int | None = None,
117
+ context: dict[str, str] | None = None,
118
+ ) -> None:
119
+ """Track scalar metrics."""
120
+ from aim import Distribution
121
+
122
+ for name, value in metrics.items():
123
+ self._run.track(
124
+ value,
125
+ name=name,
126
+ step=step,
127
+ epoch=epoch,
128
+ context=context or {},
129
+ )
130
+
131
+ def track_image(self, name: str, image: Any, step: int | None = None, epoch: int | None = None) -> None:
132
+ """Track an image (numpy array or PIL Image)."""
133
+ from aim import Image
134
+
135
+ self._run.track(Image(image), name=name, step=step, epoch=epoch)
136
+
137
+ def track_figure(self, name: str, figure: Any, epoch: int | None = None) -> None:
138
+ """Track a Plotly or Matplotlib figure.
139
+
140
+ The figure is displayed in the Aim UI under the Figures tab and can be
141
+ compared side-by-side across runs.
142
+
143
+ Args:
144
+ name: Metric name, e.g. ``"figures/confusion_matrix"``.
145
+ figure: A ``plotly.graph_objects.Figure`` or Matplotlib figure.
146
+ epoch: Optional epoch index for the Aim timeline.
147
+ """
148
+ from aim import Figure
149
+
150
+ self._run.track(Figure(figure), name=name, epoch=epoch)
151
+
152
+ def add_tag(self, tag: str) -> None:
153
+ """Add a tag to the current run."""
154
+ self._run.add_tag(tag)
155
+
156
+ def close(self) -> None:
157
+ """Finalize the run."""
158
+ self._run.close()
159
+ logger.info("Aim run closed.")
packages/softasp-core/src/softasp_core/training/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training loop, checkpointing, signals, seeds."""
2
+
3
+ from softasp_core.training.checkpointing import load_checkpoint, save_checkpoint
4
+ from softasp_core.training.seed import seed_everything
5
+ from softasp_core.training.signals import GracefulExitHandler
6
+ from softasp_core.training.trainer import Trainer
7
+
8
+ __all__ = [
9
+ "GracefulExitHandler",
10
+ "Trainer",
11
+ "load_checkpoint",
12
+ "save_checkpoint",
13
+ "seed_everything",
14
+ ]
packages/softasp-core/src/softasp_core/training/checkpointing.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checkpoint save/load with full state for bit-exact resume."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import random
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import torch
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Any real checkpoint is orders of magnitude larger; this catches empty/partial writes.
17
+ _MIN_CHECKPOINT_BYTES = 1024
18
+ _MAX_SAVE_RETRIES = 3
19
+ _SAVE_RETRY_DELAYS = (5, 15, 30) # seconds between successive attempts
20
+
21
+
22
+ def save_checkpoint(
23
+ path: Path,
24
+ *,
25
+ epoch: int,
26
+ model: torch.nn.Module,
27
+ optimizer: torch.optim.Optimizer,
28
+ scheduler: Any | None = None,
29
+ best_metric: float | None = None,
30
+ aim_run_hash: str | None = None,
31
+ scaler: torch.amp.GradScaler | None = None,
32
+ config: dict | None = None,
33
+ ) -> None:
34
+ """Save a complete checkpoint for exact resume.
35
+
36
+ Uses an atomic write-temp-then-rename pattern with post-write verification
37
+ and automatic retry. Raises RuntimeError if all retries are exhausted so
38
+ the training process exits non-zero rather than completing silently with
39
+ a missing or corrupted checkpoint.
40
+ """
41
+ state = {
42
+ "epoch": epoch,
43
+ "model_state_dict": model.state_dict(),
44
+ "optimizer_state_dict": optimizer.state_dict(),
45
+ "scheduler_state_dict": scheduler.state_dict() if scheduler else None,
46
+ "best_metric": best_metric,
47
+ "aim_run_hash": aim_run_hash,
48
+ "torch_rng_state": torch.random.get_rng_state(),
49
+ "cuda_rng_states": [torch.cuda.get_rng_state(i) for i in range(torch.cuda.device_count())]
50
+ if torch.cuda.is_available()
51
+ else [],
52
+ "numpy_rng_state": np.random.get_state(),
53
+ "python_rng_state": random.getstate(),
54
+ "scaler_state_dict": scaler.state_dict() if scaler else None,
55
+ "config": config,
56
+ }
57
+
58
+ path = Path(path)
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
61
+
62
+ last_exc: Exception | None = None
63
+ for attempt in range(1, _MAX_SAVE_RETRIES + 1):
64
+ try:
65
+ torch.save(state, tmp_path)
66
+
67
+ actual_bytes = tmp_path.stat().st_size if tmp_path.exists() else 0
68
+ if actual_bytes < _MIN_CHECKPOINT_BYTES:
69
+ raise OSError(
70
+ f"Checkpoint temp file is suspiciously small "
71
+ f"({actual_bytes} bytes): {tmp_path}"
72
+ )
73
+
74
+ tmp_path.rename(path)
75
+
76
+ if not path.exists():
77
+ raise OSError(
78
+ f"Rename appeared to succeed but final path is absent: {path}"
79
+ )
80
+
81
+ logger.info("Checkpoint saved: %s (epoch %d)", path, epoch)
82
+ return
83
+
84
+ except Exception as exc:
85
+ last_exc = exc
86
+ try:
87
+ tmp_path.unlink(missing_ok=True)
88
+ except Exception:
89
+ pass
90
+
91
+ if attempt < _MAX_SAVE_RETRIES:
92
+ delay = _SAVE_RETRY_DELAYS[attempt - 1]
93
+ logger.warning(
94
+ "Checkpoint save attempt %d/%d failed (%s) — retrying in %ds",
95
+ attempt, _MAX_SAVE_RETRIES, exc, delay,
96
+ )
97
+ time.sleep(delay)
98
+ else:
99
+ logger.error(
100
+ "Checkpoint save failed after %d attempts: %s",
101
+ _MAX_SAVE_RETRIES, path,
102
+ )
103
+
104
+ raise RuntimeError(
105
+ f"Checkpoint save failed after {_MAX_SAVE_RETRIES} attempts: {path}. "
106
+ f"Last error: {last_exc}"
107
+ ) from last_exc
108
+
109
+
110
+ def load_checkpoint(
111
+ path: Path,
112
+ *,
113
+ model: torch.nn.Module,
114
+ optimizer: torch.optim.Optimizer | None = None,
115
+ scheduler: Any | None = None,
116
+ scaler: torch.amp.GradScaler | None = None,
117
+ map_location: str | torch.device = "cpu",
118
+ weights_only: bool = False,
119
+ strict: bool = True,
120
+ ) -> dict[str, Any]:
121
+ """Load a checkpoint.
122
+
123
+ Args:
124
+ weights_only: If True, only load model weights (for pretrained_from).
125
+ strict: Passed to ``model.load_state_dict``. Use ``False`` when
126
+ loading a partial backbone checkpoint (e.g. ``backbone.pt``
127
+ which contains only ``cell_cnn.*`` keys — all other keys
128
+ are intentionally absent).
129
+
130
+ Returns:
131
+ The full checkpoint dict (caller can read epoch, best_metric, etc.).
132
+ """
133
+ logger.info("Loading checkpoint: %s", path)
134
+ ckpt = torch.load(path, map_location=map_location, weights_only=False)
135
+
136
+ if not strict:
137
+ # When strict=False filter out entries whose shape doesn't match the
138
+ # current model before calling load_state_dict. PyTorch raises a
139
+ # RuntimeError on shape mismatches even with strict=False (it only
140
+ # tolerates missing/unexpected keys). This can happen when the
141
+ # backbone was extracted with a different d_model than the consumer —
142
+ # we drop the mismatched tensors so the matching conv weights still
143
+ # load and the mismatched layers initialise from scratch.
144
+ current_sd = model.state_dict()
145
+ ckpt_sd = ckpt["model_state_dict"]
146
+ shape_skipped: list[str] = []
147
+ filtered_sd: dict = {}
148
+ for k, v in ckpt_sd.items():
149
+ if k in current_sd and current_sd[k].shape != v.shape:
150
+ shape_skipped.append(
151
+ f"{k}: ckpt={tuple(v.shape)} vs model={tuple(current_sd[k].shape)}"
152
+ )
153
+ else:
154
+ filtered_sd[k] = v
155
+ if shape_skipped:
156
+ logger.warning(
157
+ "Backbone load: skipping %d shape-mismatched key(s) (will use random init):\n %s",
158
+ len(shape_skipped),
159
+ "\n ".join(shape_skipped),
160
+ )
161
+ missing, unexpected = model.load_state_dict(filtered_sd, strict=False)
162
+ else:
163
+ missing, unexpected = model.load_state_dict(ckpt["model_state_dict"], strict=True)
164
+
165
+ if not strict and (missing or unexpected):
166
+ logger.info(
167
+ "Partial checkpoint load (strict=False): %d missing keys, %d unexpected keys.",
168
+ len(missing), len(unexpected),
169
+ )
170
+
171
+ if weights_only:
172
+ logger.info("Loaded model weights only (pretrained_from mode).")
173
+ return ckpt
174
+
175
+ if optimizer and ckpt.get("optimizer_state_dict"):
176
+ optimizer.load_state_dict(ckpt["optimizer_state_dict"])
177
+ if scheduler and ckpt.get("scheduler_state_dict"):
178
+ scheduler.load_state_dict(ckpt["scheduler_state_dict"])
179
+ if scaler and ckpt.get("scaler_state_dict"):
180
+ scaler.load_state_dict(ckpt["scaler_state_dict"])
181
+
182
+ # Restore RNG states for bit-exact reproducibility
183
+ if ckpt.get("torch_rng_state") is not None:
184
+ torch.random.set_rng_state(ckpt["torch_rng_state"])
185
+ if torch.cuda.is_available() and ckpt.get("cuda_rng_states"):
186
+ for i, state in enumerate(ckpt["cuda_rng_states"]):
187
+ if i < torch.cuda.device_count():
188
+ torch.cuda.set_rng_state(state, i)
189
+ if ckpt.get("numpy_rng_state") is not None:
190
+ np.random.set_state(ckpt["numpy_rng_state"])
191
+ if ckpt.get("python_rng_state") is not None:
192
+ random.setstate(ckpt["python_rng_state"])
193
+
194
+ logger.info("Checkpoint loaded: epoch %d, best_metric=%s", ckpt["epoch"], ckpt.get("best_metric"))
195
+ return ckpt