Broadcasting with Vector Parameters¶
PyHS3 supports broadcasting operations by allowing parameters to be vectors instead of scalars. This is useful when you want to evaluate the same model at multiple parameter points simultaneously.
Basic Usage¶
By default, most parameters are scalar tensors. However, parameters identified as observables (via likelihood data axes) are automatically created as 1D vectors to enable batched evaluation and numerical integration:
>>> import pyhs3
>>> import pytensor.tensor as pt
>>> import numpy as np
>>> # Create workspace with a simple Gaussian
>>> workspace_data = {
... "metadata": {"hs3_version": "0.2"},
... "distributions": [
... {
... "mean": "mu",
... "name": "model",
... "sigma": "sigma",
... "type": "gaussian_dist",
... "x": "x",
... }
... ],
... "parameter_points": [
... {
... "name": "default_values",
... "parameters": [
... {"name": "x", "value": 0.0},
... {"name": "mu", "value": 0.0},
... {"name": "sigma", "value": 1.0},
... ],
... }
... ],
... }
>>> ws = pyhs3.Workspace(**workspace_data)
>>> model = ws.model(0)
>>> # Scalar evaluation
>>> parameters = {"x": 0.0, "mu": 0.0, "sigma": 1.0}
>>> result = model.logpdf_unsafe("model", **parameters)
>>> print(f"Scalar result: {result}")
Scalar result: -0.9189385332046727
Converting Parameters to Vectors¶
To enable broadcasting, you need to modify the parameter’s kind before creating the model:
:options: +ELLIPSIS
>>> import warnings
>>> # Get the parameter set
>>> parameterset = ws.parameter_points[0]
>>> # Convert 'x' parameter to vector
>>> parameterset["x"].kind = pt.vector
>>> with warnings.catch_warnings(record=True) as w:
... warnings.simplefilter("always")
... # Create new model with vector parameter
... new_model = ws.model(0, parameter_set=parameterset)
... print(w[0].message) # shows the warning in the docs
...
Parameter 'x' has kind override vector (default would be scalar)
Now you can pass vector values for the x parameter:
>>> # Vector evaluation - multiple x values at once
>>> parameters = {"x": [0.0, 1.0, 2.0], "mu": 0.0, "sigma": 1.0}
>>> results = new_model.logpdf_unsafe("model", **parameters)
>>> print(f"Vector results: {results}")
Vector results: [[-0.91893853 -1.41893853 -2.91893853]]
Understanding the Model Structure¶
You can inspect the model to understand its parameter structure:
>>> print(model)
Model(
mode: CVM
parameters: 3 (...)
distributions: 1 (model)
functions: 0 ()
)
>>> # Check parameter types
>>> print(f"Parameters: {sorted(model.parameters)}")
Parameters: ['mu', 'sigma', 'x']
>>> print(f"x parameter type: {type(model.parameters['x'])}")
x parameter type: <class 'pytensor.tensor.variable.TensorVariable'>
>>> # Check parameter set configuration
>>> print(f"Parameter set: {model.context.parameter_set}")
Parameter set: ...
>>> print(f"x parameter config: {model.context.parameter_set['x']}")
x parameter config: name='x'
Behavior Difference: Scalar vs Vector Parameters¶
In the scalar model, every parameter is a 0-dimensional input. Below,
x has shape (3,) while mu and sigma each have shape ().
The scalar model does not broadcast over x: its compiled function takes
exactly one value of x. For this dimensionality mismatch,
pdf() and logpdf() raise a
ValueError naming the parameter:
>>> import numpy as np
>>> result = model.pdf(
... "model", x=np.array([0.0, 1.0, 2.0]), mu=np.array(0.0), sigma=np.array(1.0)
... )
Traceback (most recent call last):
...
ValueError: Parameter 'x' of 'model' expects a 0-dimensional array, got shape (3,).
pdf_unsafe() and logpdf_unsafe() skip
this check, so the same call through them returns the density at the first
element only:
>>> parameters = {"x": [0.0, 1.0, 2.0], "mu": 0.0, "sigma": 1.0}
>>> print(f"{model.pdf_unsafe('model', **parameters):.8f}")
0.39894228
>>> # Compare with vector model - shape (1, N): override vectors sit on axis 1
>>> result_vector = new_model.pdf_unsafe("model", **parameters)
>>> print(f"Result with vector model: {result_vector}")
Result with vector model: [[0.39894228 0.24197072 0.05399097]]
Complete Example¶
Here’s a complete working example:
:options: +ELLIPSIS
>>> import pyhs3
>>> import pytensor.tensor as pt
>>> import numpy as np
>>> import warnings
>>> # Define workspace
>>> workspace_data = {
... "metadata": {"hs3_version": "0.2"},
... "distributions": [
... {
... "mean": "mu",
... "name": "gaussian",
... "sigma": "sigma",
... "type": "gaussian_dist",
... "x": "x",
... }
... ],
... "parameter_points": [
... {
... "name": "default_values",
... "parameters": [
... {"name": "x", "value": 0.0},
... {"name": "mu", "value": 0.0},
... {"name": "sigma", "value": 1.0},
... ],
... }
... ],
... }
>>> ws = pyhs3.Workspace(**workspace_data)
>>> # Method 1: Scalar evaluation
>>> scalar_model = ws.model(0)
>>> scalar_result = scalar_model.logpdf_unsafe("gaussian", x=0.0, mu=0.0, sigma=1.0)
>>> print(f"Scalar: {scalar_result}")
Scalar: -0.9189385332046727
>>> # Method 2: Vector evaluation
>>> parameterset = ws.parameter_points[0]
>>> parameterset["x"].kind = pt.vector
>>> with warnings.catch_warnings(record=True) as w:
... warnings.simplefilter("always")
... vector_model = ws.model(0, parameter_set=parameterset)
... print(w[0].message) # shows the warning in the docs
...
Parameter 'x' has kind override vector (default would be scalar)
>>> # Evaluate at multiple x values
>>> x_values = np.linspace(-2, 2, 5)
>>> vector_results = vector_model.logpdf_unsafe(
... "gaussian", x=x_values.tolist(), mu=0.0, sigma=1.0
... )
>>> print(f"Vector: {vector_results}")
Vector: [[-2.91893853 -1.41893853 -0.91893853 -1.41893853 -2.91893853]]
Axis Convention¶
PyHS3 assigns each vector parameter a fixed axis so that broadcasting is unambiguous:
Observables (
pt.vector, axis 0): shape(N, 1)— the event dimension sits on the first axis. Summinglog_pdfoveraxis=0yields the per-parameter-point log-probability.Override vectors (
pt.vectorviakindoverride, axis 1): shape(1, M)— the scan dimension sits on the second axis. Combined with an observable(N, 1), the pdf evaluates as(N, M)and summing overaxis=0yields an(M,)NLL for each of theMparameter points.Scalars (
pt.scalar): no reshape, broadcast trivially.Constants (
pt.constant): baked at graph construction time, invisible toexplicit_graph_inputsand JAX transpilation.
As a consequence, model.log_prob has shape (M,) when parameters are
batched over M points, and is a 0-d scalar when every free parameter is a
scalar.
Current Behavior¶
Parameters identified as observables (via likelihood data axes) are automatically created as 1D vectors (
pt.vector) placed on axis 0. This enables batched evaluation and numerical integration over the observable domain.Non-observable parameters default to scalars (
pt.scalar).Users can override the default
kindon aParameterPointbefore model creation to enable parameter-scan broadcasting (axis 1). A warning is emitted when the override differs from the automatically determined default.The
kindmust be set before creating the model.
See Also¶
Evaluate a Model’s PDF and Log-PDF - Evaluating a model’s pdf/logpdf, including the
kindoverride pattern shown aboveHow pyhs3 Builds a Model - Why observables are auto-vectorized and how parameter discovery works