### Developer Installation of NengoOCL Source: https://github.com/nengo/nengo-ocl/blob/master/docs/index.md This sequence of bash commands outlines the developer installation process for NengoOCL. It involves cloning the repository, navigating into the directory, and running the setup script. This method is useful for debugging or contributing to the project. ```bash git clone https://github.com/nengo/nengo-ocl.git cd nengo-ocl python setup.py develop --user ``` -------------------------------- ### Install AMD OpenCL on Debian Unstable Source: https://github.com/nengo/nengo-ocl/blob/master/docs/index.md These bash commands demonstrate how to install AMD's OpenCL implementation on Debian unstable. It includes installing necessary packages via apt-get and then installing the PyOpenCL Python package. ```bash sudo apt-get install opencl-headers libboost-python-dev amd-opencl-icd amd-libopencl1 pip install pyopencl ``` -------------------------------- ### Install Nvidia OpenCL on Debian/Ubuntu Linux Source: https://github.com/nengo/nengo-ocl/blob/master/docs/index.md This bash command installs the Nvidia OpenCL implementation on Debian/Ubuntu systems. It ensures that the necessary OpenCL common files and libraries are installed. Users should verify driver and library version compatibility. ```bash sudo apt-get install nvidia-opencl-common nvidia-libopencl1 ``` -------------------------------- ### Install NengoOCL using pip Source: https://github.com/nengo/nengo-ocl/blob/master/docs/index.md This bash command installs the NengoOCL package and its Python dependencies using pip. It assumes a compatible Python environment and internet connection are available. ```bash pip install nengo-ocl ``` -------------------------------- ### Simulate LIF Neurons with Nengo-OCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Simulates Leaky Integrate-and-Fire (LIF) neurons using Nengo-OCL. This example configures custom time constants and refractory periods for the LIF neurons and demonstrates how to probe spikes and calculate firing rates. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: # Input current stim = nengo.Node(lambda t: 2 * np.sin(2 * np.pi * t)) # LIF ensemble with custom parameters lif_ens = nengo.Ensemble( n_neurons=100, dimensions=1, neuron_type=nengo.LIF( tau_rc=0.02, # Membrane time constant (20ms) tau_ref=0.002, # Refractory period (2ms) amplitude=1.0 # Spike amplitude ) ) nengo.Connection(stim, lif_ens) probe_decoded = nengo.Probe(lif_ens, synapse=0.01) probe_spikes = nengo.Probe(lif_ens.neurons) with nengo_ocl.Simulator(model) as sim: sim.run(1.0) spikes = sim.data[probe_spikes] total_spikes = np.sum(spikes > 0) print(f"Total spikes: {total_spikes}") print(f"Mean firing rate: {total_spikes / (1.0 * 100):.1f} Hz") ``` -------------------------------- ### Simulate RectifiedLinear Neurons with Nengo-OCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Demonstrates the use of RectifiedLinear and SpikingRectifiedLinear neurons in Nengo-OCL for rate-based and spiking computations, respectively. This example shows how to set up ensembles with these neuron types and probe their outputs. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: stim = nengo.Node(lambda t: np.sin(2 * np.pi * t)) # RectifiedLinear ensemble (rate neurons, no spiking) relu_ens = nengo.Ensemble( n_neurons=50, dimensions=1, neuron_type=nengo.RectifiedLinear(amplitude=1.0) ) # SpikingRectifiedLinear for spiking version spiking_relu_ens = nengo.Ensemble( n_neurons=50, dimensions=1, neuron_type=nengo.SpikingRectifiedLinear(amplitude=1.0) ) nengo.Connection(stim, relu_ens) nengo.Connection(stim, spiking_relu_ens) probe_relu = nengo.Probe(relu_ens, synapse=0.01) probe_spiking = nengo.Probe(spiking_relu_ens, synapse=0.01) with nengo_ocl.Simulator(model) as sim: sim.run(1.0) print(f"ReLU output range: [{sim.data[probe_relu].min():.3f}, {sim.data[probe_relu].max():.3f}]") print(f"Spiking ReLU output range: [{sim.data[probe_spiking].min():.3f}, {sim.data[probe_spiking].max():.3f}]") ``` -------------------------------- ### Implement PES Learning Rule with Nengo-OCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Shows how to implement the Prescribed Error Sensitivity (PES) learning rule for online learning in Nengo-OCL. This example trains a connection to learn a target function (x^2) and demonstrates error reduction over time. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: # Input and target signals stim = nengo.Node(lambda t: np.sin(2 * np.pi * t)) target = nengo.Node(lambda t: np.sin(2 * np.pi * t) ** 2) # Learn x^2 # Pre and post ensembles pre = nengo.Ensemble(100, 1) post = nengo.Ensemble(100, 1) nengo.Connection(stim, pre) # Learnable connection with PES rule conn = nengo.Connection( pre, post, function=lambda x: 0, # Start with zero output learning_rule_type=nengo.PES(learning_rate=1e-4) ) # Error signal for learning error = nengo.Ensemble(100, 1) nengo.Connection(post, error) nengo.Connection(target, error, transform=-1) # error = post - target nengo.Connection(error, conn.learning_rule) # Probes probe_target = nengo.Probe(target, synapse=0.01) probe_output = nengo.Probe(post, synapse=0.01) probe_error = nengo.Probe(error, synapse=0.01) with nengo_ocl.Simulator(model) as sim: sim.run(10.0) # Train for 10 seconds # Check error reduction early_error = np.mean(np.abs(sim.data[probe_error][:1000])) late_error = np.mean(np.abs(sim.data[probe_error][-1000:])) print(f"Early error: {early_error:.4f}") print(f"Late error: {late_error:.4f}") print(f"Error reduction: {(1 - late_error/early_error) * 100:.1f}%") ``` -------------------------------- ### Use Convolutional Transforms with Nengo-OCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Demonstrates the application of convolutional transforms in Nengo-OCL, suitable for image and signal processing tasks. This example sets up a convolutional ensemble and connects it to an input node, showing how to define input shape, filters, kernel size, and strides. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: # Input image (8x8 with 1 channel) input_shape = (8, 8, 1) stim = nengo.Node(output=np.random.randn(np.prod(input_shape))) # Convolutional ensemble conv = nengo.Convolution( n_filters=4, input_shape=input_shape, kernel_size=(3, 3), strides=(1, 1), padding='valid' ) a = nengo.Ensemble(conv.output_shape.size, dimensions=1) nengo.Connection(stim, a.neurons, transform=conv) probe = nengo.Probe(a.neurons) with nengo_ocl.Simulator(model) as sim: sim.run(0.1) print(f"Convolution output shape: {conv.output_shape}") print(f"Output neurons: {sim.data[probe].shape}") ``` -------------------------------- ### Reset Simulator State with reset() in Python Source: https://context7.com/nengo/nengo-ocl/llms.txt The reset() method reinitializes the simulator to its starting state, clearing all probe data and resetting signals. This is useful for running identical simulations multiple times to ensure determinism or for resetting between different experimental conditions. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: stim = nengo.Node(np.sin) ens = nengo.Ensemble(100, 1) nengo.Connection(stim, ens) probe = nengo.Probe(ens, synapse=0.01) with nengo_ocl.Simulator(model) as sim: # First simulation run sim.run(1.0) first_run_data = sim.data[probe].copy() print(f"First run: {len(first_run_data)} samples") # Reset and run again sim.reset() sim.run(1.0) second_run_data = sim.data[probe].copy() print(f"Second run: {len(second_run_data)} samples") # Results should be identical (deterministic) print(f"Data matches: {np.allclose(first_run_data, second_run_data)}") ``` -------------------------------- ### Configuring NengoOCL with Environment Variables Source: https://context7.com/nengo/nengo-ocl/llms.txt Demonstrates how to configure NengoOCL's behavior using environment variables. This includes enabling profiling, setting the sparse matrix algorithm (CSR or ELLPACK), and interactively selecting the OpenCL context. ```python import os import nengo import nengo_ocl # Enable profiling os.environ['NENGO_OCL_PROFILING'] = '1' # Set sparse matrix algorithm (CSR or ELLPACK) os.environ['NENGO_OCL_SPMV_ALGORITHM'] = 'ELLPACK' # Set OpenCL context interactively os.environ['PYOPENCL_CTX'] = '0' # Use first available device with nengo.Network() as model: ens = nengo.Ensemble(1000, 2) probe = nengo.Probe(ens) with nengo_ocl.Simulator(model) as sim: sim.run(1.0) # Profiling automatically enabled via environment variable sim.print_profiling() ``` -------------------------------- ### NengoOCL Simulator with Custom OpenCL Context and Profiling Source: https://context7.com/nengo/nengo-ocl/llms.txt Shows how to create a NengoOCL simulator with a custom OpenCL context and enable profiling to measure kernel execution times. This allows for more control over device selection and performance analysis. ```python import pyopencl as cl import nengo import nengo_ocl # Create a specific OpenCL context (interactive device selection) context = cl.create_some_context() # Alternatively, select a specific platform/device programmatically platforms = cl.get_platforms() devices = platforms[0].get_devices() context = cl.Context(devices=[devices[0]]) with nengo.Network() as model: ensemble = nengo.Ensemble(1000, dimensions=2) probe = nengo.Probe(ensemble) # Create simulator with custom options with nengo_ocl.Simulator( model, context=context, # Custom OpenCL context dt=0.001, # Time step (default: 1ms) profiling=True, # Enable profiling n_prealloc_probes=64, # Probe buffer size if_python_code='warn', # Warn if Python fallback needed ) as sim: sim.run(1.0) # Print profiling information sim.print_profiling(sort=1) # Sort by runtime ``` -------------------------------- ### Profiling and Performance Benchmarking in NengoOCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Illustrates how to use NengoOCL's built-in profiling capabilities to identify performance bottlenecks and benchmark simulation speed. It includes a warm-up run, a benchmark run with timing, and detailed kernel profiling output. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: # Large model for benchmarking ensembles = [] for i in range(10): ens = nengo.Ensemble(500, dimensions=2) ensembles.append(ens) if i > 0: nengo.Connection(ensembles[i-1], ens) probe = nengo.Probe(ensembles[-1], synapse=0.01) with nengo_ocl.Simulator(model, profiling=True) as sim: # Warm-up run sim.run(0.1) sim.reset() # Benchmark run import time start = time.time() sim.run(1.0) elapsed = time.time() - start print(f"Simulation time: {elapsed:.3f}s") print(f"Real-time factor: {1.0 / elapsed:.2f}x") # Print detailed profiling print("\nKernel profiling:") sim.print_profiling(sort=1) # Sort by runtime ``` -------------------------------- ### nengo_ocl.clra_nonlinearities.plan_probes Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md Sets up kernels for probing data at specified periods. ```APIDOC ## POST /nengo_ocl/clra_nonlinearities/plan_probes ### Description Sets up kernels for probing data at specified periods. ### Method POST ### Endpoint /nengo_ocl/clra_nonlinearities/plan_probes ### Parameters #### Query Parameters - **queue** (object) - Required - The OpenCL queue. - **periods** (list) - Required - A list of periods (in time-steps) for each probe. - **X** (object) - Required - The data to be probed. - **Y** (object) - Required - The output buffer for probed data. - **tag** (string) - Optional - A tag for the operation. ### Request Example ```json { "queue": "", "periods": [10, 20, 50], "X": "", "Y": "", "tag": "probe_setup" } ``` ### Response #### Success Response (200) - **plan** (object) - A Plan object responsible for executing the probing kernel. #### Response Example ```json { "plan": "" } ``` ``` -------------------------------- ### Run NengoOCL Simulation for a Number of Steps Source: https://context7.com/nengo/nengo-ocl/llms.txt Demonstrates the `run_steps()` method in NengoOCL, which allows simulating a model for a specific number of discrete timesteps. It also shows how to advance the simulation by a single step using the `step()` method. ```python import nengo import nengo_ocl with nengo.Network() as model: ens = nengo.Ensemble(50, 1) probe = nengo.Probe(ens) with nengo_ocl.Simulator(model, dt=0.001) as sim: # Run exactly 1000 steps sim.run_steps(1000, progress_bar=False) print(f"After {sim.n_steps} steps: time = {sim.time}s") # Single step advancement sim.step() print(f"After step(): time = {sim.time}s") ``` -------------------------------- ### SPMV Program with ELLPACK Two-Step Reduction (Python) Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md An SPMV program for the ELLPACK format that employs a two-step tree-based reduction. Partial results are stored in global memory between steps, useful when work items exceed device capacity. ```python class nengo_ocl.clra_gemv.plan_ellpack_twostep(queue, hA, X, Y, inc=False, tag=None): """SPMV program with the ELLPACK format, forces a two-step tree-based reduction. Between steps, the partial accumulants are stored in global memory. """ pass ``` -------------------------------- ### Run Nengo-OCL Tests with Py.test Source: https://github.com/nengo/nengo-ocl/blob/master/README.rst This command executes the tests for the nengo-ocl package using the py.test framework. It requires the nengo-ocl source directory to be the current working directory. Tests are run with the default OpenCL context, but can be configured using the PYOPENCL_CTX environment variable. ```bash py.test nengo_ocl/tests --pyargs nengo -v ``` -------------------------------- ### Build and Run Nengo Model with NengoOCL Simulator Source: https://github.com/nengo/nengo-ocl/blob/master/docs/index.md This Python code demonstrates how to define a Nengo model, build it using the NengoOCL simulator, run the simulation, and plot the results. It requires the nengo, nengo_ocl, and matplotlib libraries. ```python import numpy as np import matplotlib.pyplot as plt import nengo import nengo_ocl # define the model with nengo.Network() as model: stim = nengo.Node(np.sin) a = nengo.Ensemble(100, 1) b = nengo.Ensemble(100, 1) nengo.Connection(stim, a) nengo.Connection(a, b, function=lambda x: x**2) probe_a = nengo.Probe(a, synapse=0.01) probe_b = nengo.Probe(b, synapse=0.01) # build and run the model with nengo_ocl.Simulator(model) as sim: sim.run(10) # plot the results plt.plot(sim.trange(), sim.data[probe_a]) plt.plot(sim.trange(), sim.data[probe_b]) plt.show() ``` -------------------------------- ### SPMV Program with ELLPACK Format (Python) Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md An SPMV program implementation utilizing the ELLPACK sparse matrix format. This class automatically selects the most suitable algorithm based on problem size. ```python class nengo_ocl.clra_gemv.plan_ellpack(queue, hA, X, Y, inc=False, tag=None): """SPMV program with the ELLPACK format. This class chooses the implementation based on the size of the problem. """ pass ``` -------------------------------- ### Simulate Nengo Model with NengoOCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Demonstrates how to build and run a Nengo neural network model using the NengoOCL simulator for GPU acceleration. It defines a simple network with two ensembles and connections, then simulates it for 10 seconds, plotting the results. ```python import numpy as np import matplotlib.pyplot as plt import nengo import nengo_ocl # Define a neural network model with nengo.Network() as model: # Input node that outputs a sine wave stim = nengo.Node(np.sin) # Two neural populations (ensembles) of 100 neurons each a = nengo.Ensemble(100, 1) b = nengo.Ensemble(100, 1) # Connect input to first ensemble nengo.Connection(stim, a) # Connect first to second ensemble with a squaring function nengo.Connection(a, b, function=lambda x: x**2) # Add probes to record activity probe_a = nengo.Probe(a, synapse=0.01) probe_b = nengo.Probe(b, synapse=0.01) # Build and run the model with OpenCL acceleration with nengo_ocl.Simulator(model) as sim: sim.run(10) # Run for 10 seconds # Access simulation results times = sim.trange() data_a = sim.data[probe_a] data_b = sim.data[probe_b] # Plot results plt.plot(times, data_a, label='Ensemble A (sin)') plt.plot(times, data_b, label='Ensemble B (sin^2)') plt.legend() plt.show() ``` -------------------------------- ### SPMV Kernel with ELLPACK Two-Step Format (Python) Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md The OpenCL kernel implementation for a two-step sparse matrix-vector multiplication using the ELLPACK format. This is used when the number of ELL columns exceeds the capacity of a work item. ```python def nengo_ocl.clra_gemv.spmv_ellpacktwostep_impl(queue, A_columns, A_entries, X, Y, inc=False, tag=None): """SPMV kernel with the ELLPACK format, in two steps. Required when the number of ELL columns is greater than the number of workers that can fit in a work item. The first kernel is similar to `spmv_ellpack_impl`, storing partial reductions in a global array. The second kernel reduces that array, storing into `Y`. Parameters: ---------- See spmv_ellpack_impl Returns: ------- list(Plan) : Two plans corresponding to the two stages of reduction """ pass ``` -------------------------------- ### SPMV Kernel with ELLPACK Format (Python) Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md The OpenCL kernel implementation for sparse matrix-vector multiplication using the ELLPACK format. It requires column indices and entry values for the sparse matrix. ```python def nengo_ocl.clra_gemv.spmv_ellpack_impl(queue, A_columns, A_entries, X, Y, inc=False, tag=None): """SPMV kernel with the ELLPACK format. Parameters: ---------- A_columns : ELLPACK format of specifying nonzero connection indices A_entries : Matrix values at those indices X, Y : Input/output data. inc : Whether to increment `Y` (True), or set it (False). Returns: ------- Plan : Executable Plan object """ pass ``` -------------------------------- ### Run NengoOCL Simulation for a Duration Source: https://context7.com/nengo/nengo-ocl/llms.txt Illustrates the usage of the `run()` method in NengoOCL to simulate a model for a specified duration in seconds. The simulation time is rounded to the nearest timestep, and progress can be optionally displayed. ```python import nengo import nengo_ocl with nengo.Network() as model: stim = nengo.Node(lambda t: t) ens = nengo.Ensemble(100, 1) nengo.Connection(stim, ens) probe = nengo.Probe(ens, synapse=0.01) with nengo_ocl.Simulator(model) as sim: # Run for 2 seconds with progress bar sim.run(2.0, progress_bar=True) print(f"Simulated {sim.n_steps} steps, final time: {sim.time}s") # Run for additional time sim.run(1.0) print(f"Total steps: {sim.n_steps}, total time: {sim.time}s") # Access probe data print(f"Probe data shape: {sim.data[probe].shape}") ``` -------------------------------- ### SPMV Program with ELLPACK Format and Tree Reduction (Python) Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md An SPMV program using the ELLPACK format that enforces a tree-based reduction strategy. This can be beneficial for specific hardware architectures or problem structures. ```python class nengo_ocl.clra_gemv.plan_ellpack_tree(queue, hA, X, Y, inc=False, tag=None): """SPMV program with the ELLPACK format, forces a tree-based reduction. """ pass ``` -------------------------------- ### Sparse Matrix-Vector Heuristic Algorithm Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md A heuristic for choosing between CSR and ELLPACK sparse matrix formats based on memory footprint. ```APIDOC ## POST /nengo_ocl.clra_gemv.spmv_algorithm_heuristic ### Description Heuristic choosing between CSR and ELLPACK based on memory footprint. ELLPACK is preferred because it is always faster, but CSR is always less memory. The default limits are intended for use with a single device. ### Method POST ### Endpoint /nengo_ocl.clra_gemv.spmv_algorithm_heuristic ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **queue** (pyopencl.CommandQueue) - Required - Queue where the multiplication will occur. - **hA** (HostSparseMatrix) - Required - Matrix for which to implement sparse matrix-vector multiply. - **footprint_hard_limit** (float) - Optional - Proportion of total device memory above which always use CSR. Defaults to 0.8. - **footprint_soft_limit** (float) - Optional - Proportion of total device memory below which always use ELLPACK. Defaults to 0.05. - **soft_limit_ratio** (float) - Optional - Ratio of CSR to ELLPACK footprints below which CSR is selected. Defaults to 0.1. ### Request Example ```json { "queue": "", "hA": "", "footprint_hard_limit": 0.8, "footprint_soft_limit": 0.05, "soft_limit_ratio": 0.1 } ``` ### Response #### Success Response (200) - **algorithm_name** (str) - The name of the selected algorithm (e.g., 'CSR', 'ELLPACK'). #### Response Example ```json { "algorithm_name": "ELLPACK" } ``` ``` -------------------------------- ### Simulator Class Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md The Simulator class is the main interface for running Nengo models using the NengoOCL backend. It handles the conversion of Nengo models into OpenCL kernels and manages the simulation execution. ```APIDOC ## class nengo_ocl.Simulator Simulator for running Nengo models in OpenCL. ### Parameters * **network** : The Nengo network to simulate. * **dt** (float) : The time step of the simulator. Defaults to 0.001. * **seed** : Random seed for the simulation. Defaults to None. * **model** : The Nengo model to simulate. Defaults to None. * **context** : OpenCL context specifying which device(s) to run on. By default, a context is created using `pyopencl.create_some_context`. * **n_prealloc_probes** (int) : Number of timesteps to buffer when probing. Larger numbers mean less data transfer with the device (faster), but use more device memory. Defaults to 32. * **profiling** : If `True`, `print_profiling()` will show profiling information. Defaults to checking the environment variable `NENGO_OCL_PROFILING`. * **if_python_code** : How the simulator should react if a Python function cannot be converted to OpenCL code. Defaults to 'none'. * **planner** : A function to plan operator order. See `nengo_ocl.planners`. Defaults to `greedy_planner`. * **progress_bar** (bool) : Whether to display a progress bar during simulation. Defaults to True. ### Properties * **dt** (float) : The time step of the simulator. * **n_steps** (int) : The current time step of the simulator. * **time** (float) : The current time of the simulator. * **signals** : Get/set [properly-shaped] signal value (either 0d, 1d, or 2d). ### Methods #### clear_probes() Clear all probe histories. #### close() Closes the simulator. Any call to `run`, `run_steps`, `step`, and `reset` on a closed simulator raises a `nengo.exceptions.SimulatorClosed` exception. #### reset(seed=None) Reset the simulator state. * **Parameters:** * **seed** : Not implemented. Changing the simulator seed during reset is not supported by NengoOCL. #### run(time_in_seconds, progress_bar=None) Simulate for the given length of time. If the given length of time is not a multiple of `dt`, it will be rounded to the nearest `dt`. The given length of time must be positive. * **Parameters:** * **time_in_seconds** (float) : Amount of time to run the simulation for. Must be positive. * **progress_bar** : Progress bar for displaying the progress of the simulation run. If True, the default progress bar will be used. If False, the progress bar will be disabled. For more control, pass in a `nengo.utils.progress.ProgressBar` instance. #### run_steps(steps, progress_bar=True) Simulate for the given number of `dt` steps. * **Parameters:** * **steps** (int) : Number of steps to run the simulation for. * **progress_bar** (bool) : Whether to display a progress bar during simulation. Defaults to True. #### step() Advance the simulator by 1 step (`dt` seconds). ``` -------------------------------- ### Sparse Transforms in NengoOCL Source: https://context7.com/nengo/nengo-ocl/llms.txt Demonstrates efficient simulation of sparse connectivity patterns using sparse matrix operations in NengoOCL. It utilizes scipy.sparse for creating sparse matrices and nengo.Sparse for defining the connection transform. The simulation can be configured to use CSR or ELLPACK format via the NENGO_OCL_SPMV_ALGORITHM environment variable. ```python import nengo import nengo_ocl import numpy as np from scipy import sparse with nengo.Network() as model: n_pre = 1000 n_post = 500 pre = nengo.Ensemble(n_pre, dimensions=10) post = nengo.Ensemble(n_post, dimensions=10) # Create sparse connectivity (10% connection probability) density = 0.1 weights = sparse.random(n_post, n_pre, density=density, format='csr') weights.data[:] = np.random.randn(len(weights.data)) * 0.1 # Sparse transform connection nengo.Connection( pre.neurons, post.neurons, transform=nengo.Sparse( indices=np.array([weights.nonzero()]).T, data=weights.data, shape=weights.shape ) ) probe = nengo.Probe(post, synapse=0.01) # Sparse operations use ELLPACK or CSR format based on memory heuristics # Control algorithm via environment variable: NENGO_OCL_SPMV_ALGORITHM=CSR with nengo_ocl.Simulator(model) as sim: sim.run(0.5) print(f"Sparse connection with {weights.nnz} nonzero weights") print(f"Output shape: {sim.data[probe].shape}") ``` -------------------------------- ### nengo_ocl.clra_gemv.ref_impl Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md Provides a reference OpenCL function to calculate elements of a GEMV (General Matrix-Vector Multiplication) operation. ```APIDOC ## POST /nengo_ocl/clra_gemv/ref_impl ### Description Returns an OpenCL function to calculate specified items of a GEMV (General Matrix-Vector Multiplication) operation. This reference implementation uses a work grid where each item computes a portion of the output vector. ### Method POST ### Endpoint /nengo_ocl/clra_gemv/ref_impl ### Parameters #### Query Parameters - **p** (object) - Required - The GEMV operation parameters. - **items** (list) - Required - A list of items (output elements) to calculate. ### Request Example ```json { "p": "", "items": [0, 1, 2, 3] } ``` ### Response #### Success Response (200) - **ocl_function** (object) - An OpenCL function object for calculating GEMV items. #### Response Example ```json { "ocl_function": "" } ``` ``` -------------------------------- ### Sparse Matrix-Vector Multiplication Planning Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md Determines the appropriate planner for sparse matrix-vector multiplication, considering environment variables and heuristics. ```APIDOC ## POST /nengo_ocl.clra_gemv.plan_sparse_dot_inc ### Description Determines which planner to use for sparse matrix-vector multiplication. First, checks the “NENGO_OCL_SPMV_ALGORITHM” environment variable. If it is unset, uses [`spmv_algorithm_heuristic`](#nengo_ocl.clra_gemv.spmv_algorithm_heuristic) to determine the algorithm. ### Method POST ### Endpoint /nengo_ocl.clra_gemv.plan_sparse_dot_inc ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **queue** (pyopencl.CommandQueue) - Required - The command queue where the multiplication will occur. - **hA** (HostSparseMatrix) - Required - The matrix for which to implement sparse matrix-vector multiply. - **X** (Input data) - Required - Input data for multiplication. - **Y** (Output data) - Required - Output data for multiplication. - **inc** (bool) - Optional - Whether to perform an incremental update. - **tag** (any) - Optional - A tag for the operation. - **algorithm** (str) - Optional - The algorithm to use for planning. If unset, a heuristic will be used. ### Request Example ```json { "queue": "", "hA": "", "X": "", "Y": "", "inc": false, "tag": null, "algorithm": null } ``` ### Response #### Success Response (200) - **spmv_prog** (spmv_prog) - An initialized spmv_prog object from which to get plans. #### Response Example ```json { "spmv_prog": "" } ``` ``` -------------------------------- ### nengo_ocl.clra_nonlinearities.plan_conv2d Source: https://github.com/nengo/nengo-ocl/blob/master/docs/api.md Implements 2D convolution operations. ```APIDOC ## POST /nengo_ocl/clra_nonlinearities/plan_conv2d ### Description Implements 2D convolution operations, supporting various configurations including transposed convolutions and different data layouts. ### Method POST ### Endpoint /nengo_ocl/clra_nonlinearities/plan_conv2d ### Parameters #### Query Parameters - **queue** (object) - Required - The OpenCL queue. - **X** (object) - Required - Input tensor. - **Y** (object) - Required - Output tensor. - **filters** (object) - Required - Convolution filters. Format depends on `conv` and `transposed` flags. - If `conv` is True and `transposed` is False: `ch x size_i x size_j x nf` - If `conv` is True and `transposed` is True: `nf x ch x size_i x size_j` - If `conv` is False (deconvolution) and `transposed` is False: `nf x ch x size_i x size_j` - If `conv` is False and `transposed` is True: `ch x nf x size_i x size_j` - **shape_in** (tuple) - Required - Shape of the input tensor (e.g., (batch, height, width, channels)). - **shape_out** (tuple) - Required - Shape of the output tensor (e.g., (batch, out_height, out_width, out_channels)). - **kernel_shape** (tuple) - Required - Shape of the convolution kernel (e.g., (kernel_height, kernel_width)). - **conv** (boolean) - Optional - If True, performs convolution; if False, performs deconvolution. Defaults to True. - **biases** (object) - Optional - Bias terms for the convolution. Expected shape: `nf x ni x nj` (if applicable). - **padding** (tuple) - Optional - Padding to apply to the input (e.g., (pad_height, pad_width)). Defaults to (0, 0). - **strides** (tuple) - Optional - Strides for the convolution (e.g., (stride_height, stride_width)). Defaults to (1, 1). - **channels_last** (boolean) - Optional - If True, channels are the last dimension in shapes; otherwise, channels are the first. Defaults to True. - **tag** (string) - Optional - A tag for the operation. - **transposed** (boolean) - Optional - If True, performs a transposed convolution (deconvolution). Defaults to False. ### Request Example ```json { "queue": "", "X": "", "Y": "", "filters": "", "shape_in": [1, 28, 28, 3], "shape_out": [1, 26, 26, 16], "kernel_shape": [3, 3], "conv": true, "biases": null, "padding": [0, 0], "strides": [1, 1], "channels_last": true, "tag": "conv2d_op", "transposed": false } ``` ### Response #### Success Response (200) - **plan** (object) - A Plan object responsible for executing the convolution kernel. #### Response Example ```json { "plan": "" } ``` ``` -------------------------------- ### Access Simulation Data with data Property in Python Source: https://context7.com/nengo/nengo-ocl/llms.txt The data property serves as the primary interface for retrieving simulation results from probes and accessing build-time parameters. It allows easy access to decoded outputs, spike trains, neuron voltages, and model parameters like encoders. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: ens = nengo.Ensemble(100, dimensions=2) # Different types of probes probe_decoded = nengo.Probe(ens, synapse=0.01) probe_spikes = nengo.Probe(ens.neurons) probe_voltage = nengo.Probe(ens.neurons, 'voltage') with nengo_ocl.Simulator(model) as sim: sim.run(0.5) # Access different probe types decoded_output = sim.data[probe_decoded] spike_output = sim.data[probe_spikes] voltage_output = sim.data[probe_voltage] print(f"Decoded shape: {decoded_output.shape}") # (steps, dimensions) print(f"Spikes shape: {spike_output.shape}") # (steps, n_neurons) print(f"Voltage shape: {voltage_output.shape}") # (steps, n_neurons) # Access build-time parameters (e.g., encoder weights) encoders = sim.data[ens].encoders print(f"Encoders shape: {encoders.shape}") ``` -------------------------------- ### Generate Time Vectors with trange() in Python Source: https://context7.com/nengo/nengo-ocl/llms.txt The trange() method generates time vectors corresponding to the simulation steps, allowing for accurate plotting and analysis of probed data. It supports custom sampling intervals to match specific probe configurations or analysis needs. ```python import nengo import nengo_ocl import numpy as np with nengo.Network() as model: stim = nengo.Node(np.sin) ens = nengo.Ensemble(100, 1) nengo.Connection(stim, ens) # Probes with different sampling rates probe_fast = nengo.Probe(ens, synapse=0.01) probe_slow = nengo.Probe(ens, synapse=0.01, sample_every=0.01) with nengo_ocl.Simulator(model, dt=0.001) as sim: sim.run(1.0) # Get time vectors for each probe t_fast = sim.trange() # Default: every dt t_slow = sim.trange(sample_every=0.01) # Every 10ms print(f"Fast probe: {len(t_fast)} samples, {len(sim.data[probe_fast])} data points") print(f"Slow probe: {len(t_slow)} samples, {len(sim.data[probe_slow])} data points") ```