wp21-ml-utils 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: wp21_ml_utils
3
+ Version: 0.1.0
4
+ Summary: Custom TensorFlow/HGQ2 layers and models for the Global Trigger
5
+ Home-page: https://github.com/brightneedle/wp21_ml_utils.git
6
+ Author: Noah Clarke Hall
7
+ Author-email: noah.clarkehall@cern.ch
8
+ License: GNU Lesser General Public License v3 (LGPLv3)
9
+ Classifier: Development Status :: 1 - Planning
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ License-File: LICENSE
19
+ Requires-Dist: pyyaml
20
+ Requires-Dist: tensorflow>=2.16
21
+ Requires-Dist: HGQ2==0.1.8
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest; extra == "dev"
24
+ Requires-Dist: matplotlib; extra == "dev"
25
+ Requires-Dist: pre-commit; extra == "dev"
26
+ Requires-Dist: scipy; extra == "dev"
27
+ Requires-Dist: twine; extra == "dev"
28
+ Dynamic: author
29
+ Dynamic: author-email
30
+ Dynamic: classifier
31
+ Dynamic: home-page
32
+ Dynamic: license
33
+ Dynamic: license-file
34
+ Dynamic: provides-extra
35
+ Dynamic: requires-dist
36
+ Dynamic: summary
@@ -0,0 +1,307 @@
1
+ WP2.1 Machine Learning Utilities 🔧
2
+ ===================================
3
+
4
+ A compact TensorFlow/Keras utility package for HGQ-based ML studies on the
5
+ Global Trigger.
6
+
7
+ The package provides serialisable Keras layers, callable network blocks,
8
+ losses, regularisers, and configuration helpers for building detector-inspired
9
+ pipelines that operate on both sparse object vectors and dense eta-phi images.
10
+
11
+ Features
12
+ --------
13
+
14
+ - Custom Keras layers and reusable callable network blocks for quantisation,
15
+ eta-phi image conversion, pileup suppression, cone-jet reconstruction,
16
+ particle calibration, and common dense/convolutional architectures.
17
+ - Support for image-style event inputs, ``B x eta x phi x layer``, and
18
+ object-vector inputs, ``B x num_vectors x (pt, eta, phi, ...)``.
19
+ - YAML-driven model construction and compilation via
20
+ ``wp21_ml_utils.model``.
21
+ - Base classes for constructing paired training/validation datasets and
22
+ recording custom scalar objectives during Keras training.
23
+ - Keras serialisation support for the package's custom layers, losses, and
24
+ regularisers.
25
+
26
+ Installation
27
+ ------------
28
+
29
+ The package is available via ``pypi``:
30
+
31
+ .. code-block:: bash
32
+
33
+ pip install wp21_ml_utils
34
+
35
+ For development and testing, please clone and install locally via:
36
+
37
+ .. code-block:: bash
38
+
39
+ pip install -e wp21_ml_utils[dev]
40
+
41
+ Dependencies
42
+ ------------
43
+
44
+ - ``tensorflow>=2.16``
45
+ - ``HGQ2==0.1.8``
46
+ - ``pyyaml``
47
+
48
+ Core modules
49
+ ------------
50
+
51
+ - ``model.py``: load YAML configs, register custom Keras objects, build and
52
+ compile models from config dictionaries, and load saved Keras models.
53
+ - ``quantisers.py``: differentiable quantisation layers including
54
+ ``QuadLinearQuantiser``, ``FlexibleQuantiser``, and ``EncodeCellEt``.
55
+ - ``converters.py``: conversions between sparse physics vectors and dense
56
+ eta-phi images via ``VectorsToImage`` and ``ImageToVectors``.
57
+ - ``pileup.py``: pileup-suppression layers including ``TowerSoftKiller`` and
58
+ ``PileupCNN``.
59
+ - ``clustering.py``: cone-based jet reconstruction with ``ConeJet``.
60
+ - ``calibration.py``: transverse-momentum calibration with
61
+ ``CalibrationMLP``.
62
+ - ``sequential.py``: reusable callable dense and convolutional-pooling network
63
+ blocks that can be referenced from YAML configurations.
64
+ - ``layers.py``: reusable Keras layer components such as eta-phi padding,
65
+ symmetry-aware convolutions, local-maximum masks, vector sums, and monotonic
66
+ dense layers.
67
+ - ``losses.py``: custom training objectives including Chamfer, sparsity,
68
+ calibration, and pinball losses.
69
+ - ``regularisers.py``: custom Keras regularisers for weight normalisation and
70
+ sparsity.
71
+ - ``data.py``: ``BaseDataset`` interface for constructing batched training and
72
+ validation datasets.
73
+ - ``callbacks.py``: ``BaseObjective`` callback for recording user-defined
74
+ scalar scores in the Keras epoch logs.
75
+ - ``utils.py``: numerical helpers for momenta, coordinates, medians, image
76
+ augmentation, and layer initialisation.
77
+
78
+ Datasets and custom objectives
79
+ ------------------------------
80
+
81
+ Subclass ``BaseDataset`` to return batched training and validation datasets:
82
+
83
+ .. code-block:: python
84
+
85
+ import numpy as np
86
+ import tensorflow as tf
87
+ from wp21_ml_utils.data import BaseDataset
88
+
89
+ class NpzDataset(BaseDataset):
90
+ def __init__(self, path):
91
+ self.path = path
92
+
93
+ def prepare_datasets(self):
94
+ with np.load(self.path) as data:
95
+ x, y = data["cells"], data["pt_1"]
96
+ split = int(0.8 * len(x))
97
+ make_ds = lambda x, y: tf.data.Dataset.from_tensor_slices(
98
+ (x, y)
99
+ ).batch(32)
100
+ return make_ds(x[:split], y[:split]), make_ds(x[split:], y[split:])
101
+
102
+ train_ds, valid_ds = NpzDataset("train_data.npz")()
103
+
104
+ Subclass ``BaseObjective`` to add a scalar score to the epoch logs under its
105
+ ``name``:
106
+
107
+ .. code-block:: python
108
+
109
+ from wp21_ml_utils.callbacks import BaseObjective
110
+
111
+ class ValidationMSE(BaseObjective):
112
+ def __init__(self, x_valid, y_valid):
113
+ super().__init__(name="validation_mse")
114
+ self.x_valid = x_valid
115
+ self.y_valid = y_valid
116
+
117
+ def scoring_function(self):
118
+ y_pred = self.model.predict(self.x_valid, verbose=0)
119
+ return tf.reduce_mean(tf.square(self.y_valid - y_pred))
120
+
121
+ model.fit(train_ds, callbacks=[ValidationMSE(x_valid, y_valid)])
122
+
123
+ Config-driven model building
124
+ ----------------------------
125
+
126
+ Model graphs can be described in YAML. The top-level sections are:
127
+
128
+ - ``inputs``: named Keras inputs with their tensor shapes.
129
+ - ``layers``: ordered computation nodes. Each node has a ``class``, one or
130
+ more ``inputs``, and optional ``params`` passed to the constructor. The
131
+ ``class`` may be either a Keras ``Layer`` or a callable class that builds a
132
+ reusable computation block. Note that HGQ2 layer classes must be prefixed
133
+ with ``hgq>``.
134
+ - ``outputs``: named tensors to expose as model outputs, with optional loss,
135
+ metrics, and loss-weight settings used by ``compile_from_config``.
136
+ - ``optimiser``: a Keras optimiser name plus constructor parameters.
137
+ - ``hgq_config``: optional HGQ2 quantizer and layer scopes applied by
138
+ ``build_from_config`` while constructing the model.
139
+ - ``random_state``: TensorFlow seed used during model construction.
140
+
141
+ Example configuration:
142
+
143
+ .. code-block:: yaml
144
+
145
+ inputs:
146
+ cells:
147
+ shape: [null, 4] # var x (pt eta phi layer)
148
+
149
+ layers:
150
+ encode_cells:
151
+ class: EncodeCellEt
152
+ inputs: [cells]
153
+ params:
154
+ encoder_layer: QuadLinearQuantiser
155
+ encoder_config:
156
+ trainable: true
157
+
158
+ towers:
159
+ class: VectorsToImage
160
+ inputs: [encode_cells]
161
+ params:
162
+ return_layers: true
163
+ filter_layers: [0, 1, 2, 3, 4, 5]
164
+
165
+ pileup:
166
+ class: PileupCNN
167
+ inputs: [towers]
168
+
169
+ jets:
170
+ class: ConeJet
171
+ inputs: [pileup]
172
+
173
+ calib:
174
+ class: CalibrationMLP
175
+ inputs: [jets]
176
+
177
+ pt_1:
178
+ class: NthLeadingPt
179
+ inputs: [calib]
180
+ params:
181
+ index: 0
182
+
183
+ pt_4:
184
+ class: NthLeadingPt
185
+ inputs: [calib]
186
+ params:
187
+ index: 3
188
+
189
+ outputs:
190
+ pt_1:
191
+ loss: mse
192
+ metrics:
193
+ - mae
194
+ pt_4:
195
+ loss: MeanAbsoluteError
196
+ loss_weight: 0.5
197
+ metrics:
198
+ - mse
199
+ calib:
200
+ loss: CalibrationLoss
201
+ params:
202
+ sqaured: false
203
+
204
+ optimiser:
205
+ class: adam
206
+ params:
207
+ learning_rate: 0.001
208
+ clipnorm: 1.
209
+
210
+ random_state: 42
211
+
212
+
213
+ Build and compile the model from the configuration as follows:
214
+
215
+ .. code-block:: python
216
+
217
+ from wp21_ml_utils.model import (
218
+ load_config,
219
+ build_from_config,
220
+ compile_from_config,
221
+ load_model,
222
+ )
223
+
224
+ config = load_config("model_config.yaml")
225
+ model, layers, tensors = build_from_config(config)
226
+ compile_from_config(model, config)
227
+
228
+ The ``class`` values in the YAML are resolved through either registered custom
229
+ objects or standard Keras layers.
230
+
231
+ Callable classes
232
+ ~~~~~~~~~~~~~~~~
233
+
234
+ The model builder accepts both standard Keras ``Layer`` subclasses and
235
+ callable Python classes. Callable classes encapsulate reusable computation
236
+ blocks composed of multiple Keras layers. They are constructed once from the
237
+ YAML parameters and invoked on their inputs during model construction.
238
+
239
+ For example, ``DenseLayers`` and ``Conv2DPoolingLayers`` in
240
+ ``sequential.py`` are callable classes rather than Keras layers. When used in
241
+ a configuration they expand into the corresponding sequence of Keras layers,
242
+ rather than appearing as a single layer in the final model.
243
+
244
+ HGQ2 configuration
245
+ ~~~~~~~~~~~~~~~~~~
246
+
247
+ ``build_from_config`` can create the HGQ2 configuration scopes needed for
248
+ quantization-aware training. Add an optional ``hgq_config`` mapping containing:
249
+
250
+ - ``quantizer_scopes``: a list of keyword-argument mappings passed to
251
+ ``hgq.config.QuantizerConfigScope``. Scopes are entered in list order, so a
252
+ later, more specific scope can refine an earlier general scope.
253
+ - ``layer``: a keyword-argument mapping passed to
254
+ ``hgq.config.LayerConfigScope``.
255
+
256
+ Both kinds of scope remain active while every configured layer is constructed.
257
+ If ``hgq_config`` is absent, the builder creates no HGQ2 scope.
258
+
259
+ For example, this configuration sets general quantizer defaults, overrides
260
+ the weight and bias precision, configures datalane quantization, and enables
261
+ EBOPs on HGQ2 layers:
262
+
263
+ .. code-block:: yaml
264
+
265
+ hgq_config:
266
+ quantizer_scopes:
267
+ - place: all
268
+ default_q_type: kbi
269
+ overflow_mode: SAT_SYM
270
+ heterogeneous_axis: []
271
+ - q_type: kbi
272
+ place: [weight, bias]
273
+ b0: 8
274
+ i0: 2
275
+ - place: datalane
276
+ default_q_type: kif
277
+ overflow_mode: WRAP
278
+ f0: 6
279
+ layer:
280
+ enable_ebops: true
281
+ beta0: 1.0e-9
282
+
283
+ Extending the package with custom layers
284
+ ----------------------------------------
285
+
286
+ User-defined custom layers and callable computation blocks can be registered
287
+ with ``update_custom_objects``.
288
+
289
+ .. code-block:: python
290
+
291
+ from tensorflow.keras.layers import Layer
292
+ from wp21_ml_utils.model import update_custom_objects
293
+
294
+ class MyCustomLayer(Layer):
295
+ def call(self, inputs):
296
+ return inputs * 2
297
+
298
+ update_custom_objects({"MyCustomLayer": MyCustomLayer})
299
+
300
+ Registering the object before calling ``build_from_config`` allows it to be
301
+ referenced in the model configuration, whether it is a Keras ``Layer`` or a
302
+ callable class.
303
+
304
+ License
305
+ -------
306
+
307
+ BSD 2-clause
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,27 @@
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="wp21_ml_utils",
5
+ version="0.1.0",
6
+ description="Custom TensorFlow/HGQ2 layers and models for the Global Trigger",
7
+ url="https://github.com/brightneedle/wp21_ml_utils.git",
8
+ author="Noah Clarke Hall",
9
+ author_email="noah.clarkehall@cern.ch",
10
+ license="GNU Lesser General Public License v3 (LGPLv3)",
11
+ packages=["wp21_ml_utils"],
12
+ install_requires=["pyyaml", "tensorflow>=2.16", "HGQ2==0.1.8"],
13
+ extras_require={
14
+ "dev": ["pytest", "matplotlib", "pre-commit", "scipy", "twine"],
15
+ },
16
+ classifiers=[
17
+ "Development Status :: 1 - Planning",
18
+ "Intended Audience :: Science/Research",
19
+ "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ ],
27
+ )