### Clone repository and launch example notebooks Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/guide.rst Clones the AccelForge repository and starts Jupyter Notebook in the tutorials directory. Use this to explore example notebooks. ```bash git clone https://github.com/Accelergy-Project/accelforge.git cd accelforge/notebooks/tutorials jupyter notebook ``` -------------------------------- ### Install and run AccelForge tutorials Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/index.rst Quick start commands to install AccelForge with JupyterLab and ipywidgets, clone the repository, and launch the tutorial notebooks. ```bash pip install accelforge jupyterlab ipywidgets git clone https://github.com/accelergy-project/accelforge.git cd accelforge/notebooks/tutorials jupyter notebook ``` -------------------------------- ### Clone repository and list example input files Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/guide.rst Clones the AccelForge repository and lists the contents of the examples directory. Use this to view example architecture, workload, and mapping YAML files. ```bash git clone https://github.com/Accelergy-Project/accelforge.git cd accelforge/examples ls ``` -------------------------------- ### accelforge.examples Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/modules.rst Convenient variable for getting path to examples directory. ```APIDOC ## accelforge.examples ### Description Convenient variable for getting path to examples directory. ### Variable `examples = Directory(EXAMPLES_DIR)` ``` -------------------------------- ### Create flat networked architecture spec Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Builds a spec from the flat networked architecture example and a matmul workload, with N_EINSUMS set to 1. Displays the architecture. ```python spec = af.Spec.from_yaml( af.examples.arches.networked.flat, af.examples.workloads.matmuls, jinja_parse_data={"N_EINSUMS": 1}, ) spec.arch ``` -------------------------------- ### Display architecture spec for basic_analog Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Loads the basic_analog example spec and displays its architecture. Requires the _scripts helper module. ```python from _scripts import * display_important_variables("basic_analog") get_spec("basic_analog").arch ``` -------------------------------- ### Create rack-scale architecture spec Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Builds a spec from the rack-scale networked architecture example and displays the architecture. ```python spec = af.Spec.from_yaml(af.examples.arches.networked.rack) spec.arch ``` -------------------------------- ### Visualize Architecture with spec.arch Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/mapper.ipynb Displays the architecture as a tree, starting from the outermost memory level with each leaf being a Compute component. ```python spec.arch ``` -------------------------------- ### Startup boilerplate: install fibertree-bootstrap and initialize Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/understanding_looptree.ipynb Installs the fibertree-bootstrap package if not already present, then imports it and calls fibertree_bootstrap with style='uncompressed' and animation='spacetime'. This is required before using Fibertree tensors and canvas functions. ```python # Begin - startup boilerplate code import pkgutil if "fibertree_bootstrap" not in [pkg.name for pkg in pkgutil.iter_modules()]: !python3 -m pip install git+https://github.com/Fibertree-project/fibertree-bootstrap --quiet # End - startup boilerplate code from fibertree_bootstrap import * fibertree_bootstrap(style="uncompressed", animation="spacetime") ``` -------------------------------- ### Build Documentation with make generate-docs Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/contributing.rst Run this command to build the documentation site. The terminal will output a link to view the generated site, and the build should complete with zero errors and minimal warnings. ```bash make generate-docs ``` -------------------------------- ### Create hierarchical networked architecture spec Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Builds a spec from the hierarchical networked architecture example and a matmul workload, with N_EINSUMS set to 1. Displays the architecture. ```python spec = af.Spec.from_yaml( af.examples.arches.networked.hierarchical, af.examples.workloads.matmuls, jinja_parse_data={"N_EINSUMS": 1}, ) spec.arch ``` -------------------------------- ### Import accelforge and create spec from YAML examples Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/understanding_looptree.ipynb Creates an accelforge Spec by loading the simple architecture, matvecs workload, and unfused_matvecs_to_simple mapping from the built-in examples. This spec is used throughout the notebook to inspect the workload, architecture, and mapping. ```python import accelforge as af spec = af.Spec.from_yaml( af.examples.arches.simple, af.examples.workloads.matvecs, af.examples.mappings.unfused_matvecs_to_simple, ) ``` -------------------------------- ### Import accelforge Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Imports the accelforge library for use in the notebook. ```python import accelforge as af ``` -------------------------------- ### List available hwcomponents models and inspect ADC Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/component_energy_area.ipynb Use hwcomponents.get_models to list available models and their component names and actions, then use help() on the ADC model from hwcomponents_adc to get more information. The example prints the first five models and their actions. ```python import hwcomponents as hwc for model in hwc.get_models()[:5]: print(f"{model} supports {model.component_name}") for action in model.get_action_names(): print(f"\t{action}") from hwcomponents_adc import ADC help(ADC) ``` -------------------------------- ### Install AccelForge with pip Source: https://github.com/accelergy-project/accelforge/blob/main/README.md Install the AccelForge package from PyPI using pip. Requires Python 3.8 or later. ```bash pip install accelforge ``` -------------------------------- ### Create flat architecture with buffer parameters Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Builds a flat networked architecture spec with additional N_ROW_BUFFER and N_COL_BUFFER parameters set to 1. Displays the architecture. ```python spec = af.Spec.from_yaml( af.examples.arches.networked.flat, af.examples.workloads.matmuls, jinja_parse_data={"N_EINSUMS": 1, "N_ROW_BUFFER": 1, "N_COL_BUFFER": 1}, ) spec.arch ``` -------------------------------- ### Map flat architecture with buffers and plot energy Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Maps the workload to the flat architecture with buffer parameters and plots the energy breakdown by component and tensor. ```python result = spec.map_workload_to_arch() plot_energy_breakdown([result], separate_by=["component"], stack_by=["tensor"]) ``` -------------------------------- ### Display energy per component Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Shows the energy breakdown per component from the mapping result. ```python result.energy(per_component=True) ``` -------------------------------- ### Map flat architecture and display result Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Maps the workload to the flat architecture and displays the result object. ```python result = spec.map_workload_to_arch() result ``` -------------------------------- ### Display mapping result data Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Shows the raw data from the mapping result. ```python result.data ``` -------------------------------- ### Map workload to architecture with latency and energy metrics Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Sets the mapper metrics to LATENCY and ENERGY, then maps the workload to the architecture. The result is stored for later inspection. ```python spec.mapper.metrics = af.mapper.Metrics.LATENCY | af.mapper.Metrics.ENERGY result = spec.map_workload_to_arch() ``` -------------------------------- ### Run Test Suite with unittest Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/contributing.rst Run this command to execute the test suite. It discovers and runs all tests in the tests directory matching the pattern '*.py' with verbose output. ```bash python3 -m unittest discover -s tests -p "*.py" -v ``` -------------------------------- ### Display hop-related columns from result data Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Shows only the columns in the result data that contain 'hops' in their names. ```python result.data[[c for c in result.data.columns if "hops" in c]] ``` -------------------------------- ### Plot energy breakdown by component and tensor Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/networks.ipynb Uses plot_energy_breakdown to visualize the energy breakdown, separating by component and stacking by tensor. ```python from accelforge.plotting.mappings import plot_energy_breakdown plot_energy_breakdown([result], separate_by=["component"], stack_by=["tensor"]) ``` -------------------------------- ### Get documentation for the component model Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/component_energy_area.ipynb Retrieves the `component_model` attribute and prints its help documentation to understand the model used for calculations. ```python # < DOC_INCLUDE_MARKER > hwcomponents component_model = global_buffer.component_model print(help(component_model)) # Get documentation for the model ``` -------------------------------- ### YAML LoopTree mapping example Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/spec/mapping.rst Shows a complete LoopTree mapping in YAML for a cascade of two matrix-vector multiplications on an architecture with OffChipBuffer, OnChipBuffer, and ComputeUnit. It includes storage, temporal, sequential, nested, and compute nodes. The mapping is used as input/output to AccelForge. ```yaml mapping: nodes: - !Storage component: OffChipBuffer tensors: [I, WA, WB, B] - !Storage component: OnChipBuffer tensors: [WA] - !Temporal rank_variable: nA tile_shape: 1 - !Storage component: OnChipBuffer tensors: [A] - !Sequential nodes: - !Nested nodes: - !Temporal rank_variable: nI tile_shape: 1 - !Storage component: OnChipBuffer tensors: [I] - !Compute einsum: EinsumA component: ComputeUnit - !Nested nodes: - !Temporal rank_variable: nB tile_shape: 1 - !Storage component: OnChipBuffer tensors: [B, WB] - !Compute einsum: EinsumB component: ComputeUnit ``` -------------------------------- ### Load unfused mapping spec with af.Spec.from_yaml Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/model.ipynb Loads a simple architecture, a chain of matrix multiplications, and an unfused mapping using AccelForge's Spec.from_yaml. The jinja_parse_data provides parameters for the example files, including N_EINSUMS, M, KN, MainMemoryEnergy, and GlobalBufferSize. ```python import accelforge as af spec = af.Spec.from_yaml( af.examples.arches.simple, af.examples.workloads.basic.matmuls, af.examples.mappings.unfused_matmuls_to_simple, jinja_parse_data={ "N_EINSUMS": 2, "M": 64, "KN": 32, "MainMemoryEnergy": 40, "GlobalBufferSize": 1e5, }, ) ``` -------------------------------- ### Display annotated component YAML file Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/component_energy_area.ipynb Reads the annotated component YAML file and displays it as a Markdown code block in the notebook. Requires the examples directory path. ```python from pathlib import Path from IPython.display import Markdown examples_dir = Path("../../examples") display( Markdown( f""" ```yaml {open(examples_dir / "misc" / "component_annotated.yaml").read()} ``` """ ) ) ``` -------------------------------- ### Define Global Buffer Size Range Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/design_space_exploration.ipynb Creates a list of 32 logarithmically spaced global buffer sizes from 32 bytes to 4MB. The sizes are in bits, starting at 256 bits and ending at 33,554,432 bits. ```python size_start = 32 * 8 # 32 bytes size_end = 4 * 1024 * 1024 * 8 # 4MB n_sizes = 32 # Number of sizes to explore sizes = [ size_start * (size_end / size_start) ** (i / (n_sizes - 1)) for i in range(n_sizes) ] ``` -------------------------------- ### Setup and display Colonnade architecture variables Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/colonnade_jssc_2021.ipynb Initializes the notebook environment and displays important variables and the architecture specification for the 'colonnade_jssc_2021' test. ```python from _scripts import * from tqdm.auto import tqdm display_important_variables("colonnade_jssc_2021") get_spec("colonnade_jssc_2021").arch ``` -------------------------------- ### Workload YAML example with rank sizes, iteration space, bits, persistent tensors, and einsums Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/spec/workload.rst Defines a workload with three back-to-back matrix multiplications. Includes rank_sizes, iteration_space_shape constraints, bits_per_value, persistent_tensors, and a list of einsums with tensor accesses and renames. The renames section maps generic names (input, output, weight) to source set expressions with expected counts. ```yaml workload: # These rank sizes define the shapes of the tensors in the Einsum. Shapes are assumed # to go from [0, size-1]. Indexes into a rank are omitted if out of range. rank_sizes: M: 128 N0: 128 N1: 128 N2: 128 N3: 128 # Alternatively, we can constrain each of the rank variables to be within a range. The # values in this dictionary are ISL expressions, and the constraints apply to all # Einsums that use these rank variables. iteration_space_shape: m: 0 <= m < 128 n0: 0 <= n0 < 128 n1: 0 <= n1 < 128 n2: 0 <= n2 < 128 n3: 0 <= n3 < 128 # Describe the number of bits of each value of each tensor. This is a dictionary of # set expressions to bits per value for the tensors given by those expressions. They # can be overridden by the bits_per_value attribute of any tensor access. bits_per_value: {All: 8} # Mark tensors as persistent if they must live in their backing storage for the entire # workload's execution. persistent_tensors: weight - Intermediates # The Einsums in the workload. einsums: - name: Matmul1 tensor_accesses: - {name: T0, projection: [m, n0]} - {name: W0, projection: [n0, n1]} - {name: T1, projection: [m, n1], output: True} renames: {input: T0} - name: Matmul2 tensor_accesses: - {name: T1, projection: [m, n1]} - {name: W1, projection: [n1, n2]} - {name: T2, projection: [m, n2], output: True} - name: Matmul3 tensor_accesses: - {name: T2, projection: [m, n2]} - {name: W2, projection: [n2, n3]} - {name: T3, projection: [m, n3], output: True} renames: einsums: - name: default tensor_accesses: - name: input source: Inputs & Intermediates expected_count: 1 - name: output source: Outputs expected_count: 1 - name: weight source: ~(input | output) expected_count: 1 ``` -------------------------------- ### Setup and Display Architecture for RAELLA ISCA 2023 Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/raella_isca_2023.ipynb Initializes the RAELLA ISCA 2023 specification and displays its architecture. Used to set up the environment for subsequent speculation analysis. ```python from _scripts import * from tqdm.auto import tqdm display_important_variables("raella_isca_2023") get_spec("raella_isca_2023").arch ``` -------------------------------- ### Load Albireo ISCA 2021 architecture and display variables Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/albireo_isca_2021.ipynb Initializes the Albireo ISCA 2021 example by importing helper functions and displaying the architecture specification. Uses the `_scripts` module and `tqdm` for progress bars. ```python from _scripts import * from tqdm.auto import tqdm display_important_variables("albireo_isca_2021") get_spec("albireo_isca_2021").arch ``` -------------------------------- ### Create custom MAC ComponentModel with low leakage and use it Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/component_energy_area.ipynb Define a custom hwcomponents.ComponentModel subclass named MyMac with a very low leak power, then assign it to the MAC component in the spec and recalculate costs. The example also prints the component modeling log messages. Requires the hwcomponents library and an existing spec from af.Spec.from_yaml. ```python # Create a hwcomponents model. See the hwcomponents tutorial for ore information on how # to make these! import hwcomponents as hwc class MyMac(hwc.ComponentModel): component_name: str = "intmac" priority: float = 0.5 def __init__(self): super().__init__(area=5e-8, leak_power=1e-12) # Very low leakage power @hwc.action def compute(self) -> hwc.ActionCost: self.logger.info(f"*** Getting compute energy ***") # 1pJ, 1ns return hwc.ActionCost(energy=1e-12, throughput=1 / 1e-9, latency=1e-9) # Initialize the spec and make the MAC use our custom model spec = af.Spec.from_yaml(examples_dir / "arches" / "eyeriss.yaml") mac = spec.arch.find("MAC") mac.component_model = MyMac() # Calculate the energy and area of the MAC and print out the results mac = mac.calculate_component_costs() print(f"MAC area: {mac.area:.2e} m^2") print(f"MAC leak power: {mac.leak_power:.2e} W") for action in mac.actions: print( f"{action.name} energy: {action.energy:.2e} J, throughput {action.throughput:.2e} actions/s" ) # The energy and area log contain logs from the ComponentModel component. print(f"Log messages: ") for message in mac.component_modeling_log: print(f"\t{message}") ``` -------------------------------- ### Create tensors, set colors, and run unfused matvec animation Source: https://github.com/accelergy-project/accelforge/blob/main/tests/not_working/understanding_looptree.ipynb Builds tensors from the spec, sets B and C to green, gets roots for all tensors, creates a canvas, and runs the unfused matrix-vector multiplication loops. Adds activity and frames to the canvas, then displays it. The darker highlight shows elements used in computation; lighter highlight shows what is resident in the GlobalBuffer. ```python tensor_name_to_fibertree_tensor = make_tensors_from_spec(spec) A = tensor_name_to_fibertree_tensor["A"] Y = tensor_name_to_fibertree_tensor["Y"] Z = tensor_name_to_fibertree_tensor["Z"] B = tensor_name_to_fibertree_tensor["B"] B.setColor("green") C = tensor_name_to_fibertree_tensor["C"] C.setColor("green") a = A.getRoot() y = Y.getRoot() z = Z.getRoot() b = B.getRoot() c = C.getRoot() canvas = createCanvas(A, Y, Z) for ny in range(3): for na in range(4): y[ny] += a[na] * b[na][ny] canvas.addActivity([], [(ny,)], [], worker="Y in GlobalBuffer") canvas.addFrame([(na,)], [(ny,)], []) for ny in range(3): for nz in range(4): z[nz] += y[ny] * c[ny][nz] canvas.addActivity([], [(ny,)], [], worker="Y in GlobalBuffer") canvas.addFrame([], [(ny,)], [(nz,)]) displayCanvas(canvas) ``` -------------------------------- ### Configure and run fused vs. unfused mapping for GPT-3 6.7B Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/memory_size_vs_access_tradeoff.ipynb Sets up an AccelForge spec with a GPT-3 6.7B attention head workload (2048 tokens) and runs mapping twice: once with fused tensors (keeping only non-intermediate tensors in MainMemory) and once with unfused (keeping all tensors). Requires the 'accelforge' package and example files; may take 3-15 minutes to run. ```python import accelforge as af from pathlib import Path examples_dir = Path("../../examples") spec = af.Spec.from_yaml( af.examples.arches.snowcat, af.examples.workloads.transformers.gpt.gpt3_6_7B, # af.examples.workloads.three_matmuls_annotated, jinja_parse_data={"BATCH_SIZE": 1, "DECODE": False, "N_NEW_TOKENS": 2048}, ) spec.mapper.metrics = af.Metrics.ENERGY | af.Metrics.RESOURCE_USAGE # FUSED spec.arch.find("MainMemory").tensors.keep = "~Intermediates" spec.arch.find("MainMemory").tensors.may_keep = "All" results_fused = spec.map_workload_to_arch() # UNFUSED spec.arch.find("MainMemory").tensors.keep = "All" results_unfused = spec.map_workload_to_arch() ``` -------------------------------- ### Display Snowcat Architecture YAML Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/memory_size_vs_access_tradeoff.ipynb Loads and displays the snowcat architecture file from the AccelForge examples using IPython Markdown. This is part of the Orojenesis analysis setup. ```python from IPython.display import Markdown, display import accelforge as af display( Markdown( f""" ``` yaml {open(af.examples.arches.snowcat).read()} ``` """ ) ) ``` -------------------------------- ### Inspect Mapping Energy and Latency Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/mapper.ipynb Prints the total and per-compute energy and latency of the mapping, including per-component breakdowns. ```python # < DOC_INCLUDE_MARKER > mapping_stats print(f"Energy: {mapping.energy()}J, {mapping.per_compute().energy()}J/compute") for k, v in mapping.per_compute().energy(per_component=True).items(): print(f"\t{k}: {v}J/compute") print(f"Latency: {mapping.latency()}s, {mapping.per_compute().latency()}s/compute") for k, v in mapping.per_compute().latency(per_component=True).items(): print(f"\t{k}: {v}s/compute") ``` -------------------------------- ### Visualize Workload with spec.workload Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/mapper.ipynb Displays the workload as a cascade of Einsums, with boxes for computation steps, ovals for tensors, and arrows for dependencies. ```python spec.workload ``` -------------------------------- ### Map Workload to Architecture with spec.map_workload_to_arch Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/mapper.ipynb Maps the workload onto the architecture in one step. Setting max_fused_loops to 1 limits fused loops per pmapping, which may be slower but can generate better mappings. ```python # < DOC_INCLUDE_MARKER > map_workload_to_arch # Commenting this will be slower, but may generate better mappings. Limits the number of # fused loops that can exist in a single pmapping. spec.mapper.max_fused_loops = 1 mapping = spec.map_workload_to_arch() # Render the mapping with mapping.render(), or in the last line of a notebook: mapping ``` -------------------------------- ### Configure and map ResNet-18 workload on basic analog macro Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Sets up a ResNet-18 workload with batch size 1, configures a basic analog macro with a larger 512x64 array, and maps the workload to the architecture to compute per-einsum energy breakdown. The mapper uses energy metrics and disables loop order exploration. The result is filtered to drop components with zero energy and latency, then plotted as a stacked bar chart of per-einsum energy in fJ/MAC. The highest-energy einsum is printed. ```python workload_path = af.examples.workloads.compute_in_memory.resnet18 workload = af.Workload.from_yaml( workload_path, top_key="workload", jinja_parse_data={"BATCH_SIZE": 1} ) renames = af.Renames.from_yaml( workload_path, top_key="renames", jinja_parse_data={"BATCH_SIZE": 1} ) spec = get_spec("basic_analog", add_dummy_main_memory=True, n_macros=1) spec.workload = workload spec.renames = renames # Use a larger array (512 rows x 64 cols) to ensure we can fit all weights. spec.arch.find_spatial("row_ARRAY_ROWS").fanout = 512 spec.arch.find_spatial("column_ARRAY_COLUMNS").fanout = 64 spec.workload = workload spec.renames = renames spec.mapper.metrics = af.Metrics.ENERGY spec.mapper.explore_loop_orders = False result = spec.map_workload_to_arch(one_pbar_only=True) result = result.drop_components_with_zero_energy_and_latency() fig, ax = plt.subplots(figsize=(20, 5)) energy = result.per_compute().energy(per_component=True, per_einsum=True) for_plot = {} for (einsum, component), v in energy.items(): for_plot.setdefault(einsum, {})[component] = float(v) * 1e15 bar_stacked( for_plot, title="Per-Einsum Energy Breakdown", xlabel="Einsum", ylabel="Energy (fJ/MAC)", ax=ax, ) plt.tight_layout() plt.show() per_einsum_energy = result.energy(per_einsum=True) highest_energy_einsum = max( per_einsum_energy, key=lambda k: float(per_einsum_energy[k]), ) print(f"Highest-energy Einsum: {highest_energy_einsum}") ``` -------------------------------- ### Initialize Spec with af.Spec.from_yaml Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/mapper.ipynb Initializes the spec using YAML files with Jinja2 templating. Sets the number of parallel threads for the mapper and optionally disables fusion by keeping all tensors in the outermost memory. ```python from pathlib import Path examples_dir = Path("../../examples") # < DOC_INCLUDE_MARKER > make_spec import accelforge as af # Set the number of parallel threads that the mapper can use. If you are running out of # memory, you may decrease this number. By default the number of threads is set to the # number of cores on your machine. import os af.set_n_parallel_jobs(os.cpu_count(), print_message=True) # Initialize the spec and show the workload. BATCH_SIZE = 1 N_TOKENS = 2048 FUSE = False spec = af.Spec.from_yaml( af.examples.arches.tpu_v4i, af.examples.workloads.transformers.gpt.gpt3_6_7B, jinja_parse_data={"BATCH_SIZE": BATCH_SIZE, "DECODE": False, "N_NEW_TOKENS": N_TOKENS}, ) # Fusion happens when tensors bypass the outermost Memory object, so, to disable fusion, # force all tensors to be in the outermost memory. if not FUSE: for node in spec.arch.nodes: if isinstance(node, af.arch.Memory): print(f"Keeping all tensors in {node.name}") node.tensors.keep = "All" break ``` -------------------------------- ### Run basic analog accelerator mapping Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Loads the basic_analog spec, workload, and renames, sets the mapper to explore only energy, disables loop order exploration, maps the workload to the architecture, and displays the results. The CiM array is fully utilized; ADC and row drivers dominate energy and latency. ```python basic_analog = af.examples.arches.compute_in_memory.basic_analog workload = af.Workload.from_yaml(basic_analog, top_key="workload") renames = af.Renames.from_yaml(basic_analog, top_key="renames") spec = get_spec("basic_analog", add_dummy_main_memory=True, n_macros=1) spec.workload = workload spec.workload.einsums = spec.workload.einsums spec.renames = renames spec.mapper.metrics = af.Metrics.ENERGY # It's OK to explore loop orders, but will make the search take longer, and is not very # helpful for CiM accelerators. It's not very helpful because loop orders help us # capture sliding window reuse, and the CiM macros consume very big tiles at once, # giving limited benefit from the small overlap between each tile. spec.mapper.explore_loop_orders = False result = spec.map_workload_to_arch() result = result.drop_components_with_zero_energy_and_latency() display_dnn_results(result, title="Basic Analog Results") ``` -------------------------------- ### Set Optimization Metrics Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/mapper.ipynb Sets the mapper's optimization metric to ENERGY. Fewer metrics speed up pruning of suboptimal mappings; a mapping is suboptimal if another is better in all metrics. ```python # Set optimization metrics spec.mapper.metrics = af.mapper.Metrics.ENERGY # spec.mapper.metrics = af.mapper.Metrics.LATENCY # spec.mapper.metrics = af.mapper.Metrics.ENERGY_DELAY_PRODUCT ``` -------------------------------- ### Display YAML architecture file for basic_analog Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Reads the basic_analog architecture YAML file and renders it as a Markdown code block. Uses the af.examples.arches.compute_in_memory.basic_analog path. ```python txt = open(af.examples.arches.compute_in_memory.basic_analog).read() display( Markdown( f""" ```yaml {txt} ``` """ ) ) ``` -------------------------------- ### YAML compute node format Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/spec/mapping.rst Shows the YAML format for a compute node, using the !Compute tag with einsum and component keys. This is a minimal example of a node type in LoopTree notation. ```yaml !Compute # this is a YAML tag einsum: name-of-einsum-to-compute # a YAML dictionary element "key: value" component: name-of-compute-component-that-processes-the-einsum ``` -------------------------------- ### Plot energy breakdown by component and Einsum Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/model.ipynb Further breaks down energy consumption by Einsum using stack_by parameter. ```python plot_energy_breakdown([result], separate_by=["component"], stack_by=["einsum"]) ``` -------------------------------- ### Get Per-Component Latency for Speculation True Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/raella_isca_2023.ipynb Returns the latency breakdown per component for the speculation-enabled run. Helps identify which components contribute most to overall latency. ```python results["Speculation True"].latency(per_component=True) ``` -------------------------------- ### Setup and Display Architecture for sinangil_jssc_2021 Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/sinangil_jssc_2021.ipynb Initializes the notebook environment and displays the architecture specification for the 'sinangil_jssc_2021' macro. Use this to load the spec and inspect its architecture before running validation tests. ```python from _scripts import * display_important_variables("sinangil_jssc_2021") get_spec("sinangil_jssc_2021").arch ``` -------------------------------- ### Plot energy breakdown by component and Einsum for fused mapping Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/model.ipynb Breaks down energy consumption by Einsum for the fused result. ```python plot_energy_breakdown([fused_result], separate_by=["component"], stack_by=["einsum"]) ``` -------------------------------- ### YAML expression evaluation example Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/parsing/evaluation.rst Shows valid evaluated data in YAML. Variables can reference top-level variables, outer-scope variables, and other keys in the same object as long as references are not cyclic. Statements can be out-of-order if not cyclic referencing. ```yaml variables: a: 123 b: a + 5 c: min(b, 3) d: sum(y for y in range(1, 10)) # In some later scope ... outer_scope: x: 123 y: a + x # Reference top-level variables inner_scope: a: 3 # Override outer scope b: outer_scope.x # Statements can be out-of-order if not cyclic referencing firt_item: second_item second_item: 3 ``` -------------------------------- ### Plot area breakdown Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/isaac_isca_2016.ipynb Gets the area breakdown for the ISAAC accelerator, converts to um², plots a bar chart, and prints sorted area values with percentages and total. Area is dominated by the ADC. ```python area = get_area_breakdown("isaac_isca_2016") area_um2 = {k: v * 1e12 for k, v in area.items() if v > 0} fig, ax = plt.subplots(figsize=(10, 5)) bar(area_um2, "Component", "Area (um\u00b2)", "ISAAC Area Breakdown", ax) plt.tight_layout() plt.show() total = sum(area_um2.values()) for k, v in sorted(area_um2.items(), key=lambda x: -x[1]): print(f"{k}: {v:.1f} um\u00b2 ({v/total*100:.1f}%)") print(f"Total: {total:.1f} um\u00b2 ({total/1e6:.4f} mm\u00b2)") ``` -------------------------------- ### Commented Out Direct Mapping Loop Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/design_space_exploration.ipynb Shows a slower, direct approach to mapping each size sequentially, which is commented out in favor of parallelization. ```python # < SLOWER > # Directly use the function # results = {size: get_mapper_result(spec, size) for size in sizes} ``` -------------------------------- ### Plot Energy per Compute vs Global Buffer Size Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/design_space_exploration.ipynb Plots the energy per compute (in pJ) against global buffer size on a log scale. Expect a U-shaped curve with a minimum around 2e5 bits (24kB). ```python from typing import Any import matplotlib.pyplot as plt x = list(results.keys()) y = [v.per_compute().energy() * 1e12 for v in results.values()] plt.plot(x, y) plt.xlabel("Global Buffer Size (bits)") plt.ylabel("Energy per Compute (pJ)") plt.xscale("log") plt.show() ``` -------------------------------- ### Voltage scaling sweep and plots Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Sweeps supply voltage from 0.55V to 1.50V, runs the mapper for each voltage, and plots energy efficiency (TOPS/W) and throughput (TOPS) versus voltage. Expects energy efficiency to drop and throughput to rise as voltage increases due to quadratic energy scaling and linear latency scaling. ```python voltages = [v / 100 for v in range(55, 155, 5)] voltage_results = parallel( [ delayed(_run_basic_analog_variables)(top_variables={"voltage": v}) for v in voltages ] ) tops_per_w_by_v = { f"{v:.2f}V": 2 / r.per_compute().energy() / 1e12 for v, r in zip(voltages, voltage_results) } tops_by_v = { f"{v:.2f}V": 2 / r.per_compute().latency() / 1e12 for v, r in zip(voltages, voltage_results) } fig, ax = plt.subplots(1, 2, figsize=(12, 5)) ax[0].plot(voltages, list(tops_per_w_by_v.values()), "o-") ax[0].set_xlabel("Supply Voltage (V)") ax[0].set_ylabel("Energy Efficiency (TOPS/W)") ax[0].set_title("Supply Voltage vs. Energy Efficiency") ax[0].grid(alpha=0.3) ax[1].plot(voltages, list(tops_by_v.values()), "s-") ax[1].set_xlabel("Supply Voltage (V)") ax[1].set_ylabel("Throughput (TOPS)") ax[1].set_title("Supply Voltage vs. Throughput") ax[1].grid(alpha=0.3) plt.tight_layout() plt.show() ``` -------------------------------- ### Create and evaluate an unfused mapping with accelforge Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/access_trace.ipynb Builds a specification from YAML example files for a chain of matrix multiplications mapped onto the simple architecture without fusion, then evaluates the mapping. The jinja_parse_data parameter sets N_EINSUMS=2, M=4, and KN=3. ```python import accelforge as af spec = af.Spec.from_yaml( af.examples.arches.simple, af.examples.workloads.basic.matmuls, af.examples.mappings.unfused_matmuls_to_simple, jinja_parse_data={"N_EINSUMS": 2, "M": 4, "KN": 3}, ) results = spec.evaluate_mapping() ``` -------------------------------- ### Run basic_analog spec with varying array sizes and plot energy/throughput Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Defines run_basic_analog_spec to load the basic_analog spec, resize the array, run the mapper, and return results. Sweeps row and column choices, computes energy efficiency and throughput, and plots them. The mapper explores loop orders disabled to speed up search. ```python import numpy as np def run_basic_analog_spec(array_rows: int, array_columns: int): """Load basic_analog, resize the array, run the mapper, and return the result.""" spec = get_spec("basic_analog", add_dummy_main_memory=True, n_macros=1) # Set the number of rows and columns in the array. spec.arch.find_spatial("row_ARRAY_ROWS").fanout = array_rows spec.arch.find_spatial("column_ARRAY_COLUMNS").fanout = array_columns # Match the workload to the array for a max-utilization test. spec.workload.einsums["Matmul"].rank_sizes["K"] = array_rows spec.workload.einsums["Matmul"].rank_sizes["N"] = array_columns spec.mapper.metrics = af.Metrics.ENERGY # It's OK to explore loop orders, but will make the search take longer, and # is not very helpful for CiM accelerators. spec.mapper.explore_loop_orders = False result = spec.map_workload_to_arch(print_progress=False) return result.drop_components_with_zero_energy_and_latency() row_choices = [16, 32, 64, 128] col_choices = [16, 32, 64, 128] all_results = parallel( [ delayed(run_basic_analog_spec)(array_rows=r, array_columns=c) for r in row_choices for c in col_choices ] ) def _tops_per_w(r): return 2 / (float(r.energy()) / float(r.n_computes())) / 1e12 def _tops_per_mm2(r, rows, cols): area_m2 = sum(get_area_breakdown("basic_analog").values()) spec = get_spec("basic_analog") spec.arch.find_spatial("row_ARRAY_ROWS").fanout = rows spec.arch.find_spatial("column_ARRAY_COLUMNS").fanout = cols spec.workload.einsums["Matmul"].rank_sizes["K"] = rows spec.workload.einsums["Matmul"].rank_sizes["N"] = cols evaluated = spec.calculate_component_costs() area_m2 = sum(float(v) for v in evaluated.arch.per_component_total_area.values()) tops = 2 / (float(r.latency()) / float(r.n_computes())) / 1e12 return tops / (area_m2 * 1e6) if area_m2 > 0 else 0.0 energy_efficiency_grid = np.zeros((len(row_choices), len(col_choices))) throughput_grid = np.zeros((len(row_choices), len(col_choices))) idx = 0 for i, rows in enumerate(row_choices): for j, cols in enumerate(col_choices): r = all_results[idx] idx += 1 energy_efficiency_grid[i, j] = _tops_per_w(r) throughput_grid[i, j] = _tops_per_mm2(r, rows, cols) fig, ax = plt.subplots(figsize=(10, 5), ncols=2) for subplot, target, title in [ (0, energy_efficiency_grid, "Energy Efficiency (TOPS/W)"), (1, throughput_grid, "Throughput (TOPS/mm^2)"), ]: im = ax[subplot].imshow(target, cmap="hot", aspect="auto") ax[subplot].set_title(title) ax[subplot].set_xlabel("Array Columns") ax[subplot].set_ylabel("Array Rows") ax[subplot].set_xticks(np.arange(len(col_choices))) ax[subplot].set_yticks(np.arange(len(row_choices))) ax[subplot].set_xticklabels(col_choices) ax[subplot].set_yticklabels(row_choices) ax[subplot].set_ylim(ax[subplot].get_ylim()[::-1]) fig.colorbar(im, ax=ax[subplot]) plt.tight_layout() plt.show() ``` -------------------------------- ### Run SRAM and RRAM device scenarios for analog CiM macro Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/compute_in_memory/tutorial_basic_analog.ipynb Defines paths to SRAM and RRAM cell configuration YAML files and a helper function that runs both device scenarios for a given cycle time, computes per-component energy, and plots a stacked bar chart. The SRAM scenario uses 1 bit per cell with 4 cells per CiM unit, while the RRAM scenario uses 4 bits per cell with 1 cell per CiM unit. The function is called with a 1e-7 s (100 ns) cycle time for the fast scenario. ```python import os SRAM_PATH = os.path.abspath( os.path.join( os.path.dirname(af.examples.arches.compute_in_memory.basic_analog), "memory_cells", "sram_example.yaml", ) ) RRAM_PATH = os.path.abspath( os.path.join( os.path.dirname(af.examples.arches.compute_in_memory.basic_analog), "memory_cells", "rram_example.yaml", ) ) def _run_device_scenario(cycle_seconds, title): """Run SRAM and RRAM scenarios for the given cycle time; plot the breakdown.""" device_specs = [ ( "SRAM", {"cell_config": af.LiteralString(SRAM_PATH)}, { "bits_per_cell": 1, "cim_unit_width_cells": 4, "cycle_period": cycle_seconds, }, ), ( "RRAM", {"cell_config": af.LiteralString(RRAM_PATH)}, { "bits_per_cell": 4, "cim_unit_width_cells": 1, "cycle_period": cycle_seconds, }, ), ] results = parallel( [ delayed(_run_basic_analog_variables)( top_variables=tops, arch_variables=arch, array_rows=512, array_cols=512, ) for _, tops, arch in device_specs ] ) energies = {} for (label, _, _), r in zip(device_specs, results): breakdown = r.per_compute().energy(per_component=True) energies[label] = {k: float(v) * 1e15 for k, v in breakdown.items() if v > 0} fig, ax = plt.subplots(figsize=(8, 5)) bar_stacked( energies, title=title, xlabel="Device Type", ylabel="Energy (fJ/MAC)", ax=ax, ) plt.tight_layout() plt.show() return energies display_markdown( """ First, we run a **fast** scenario, in which the macro is run with a 1e-7 s (100 ns) cycle time. The energy breakdown for the fast scenario is shown below. """ ) fast_energy = _run_device_scenario(1e-7, "Fast Scenario (100 ns cycle)") ``` -------------------------------- ### Create and calculate costs for a single component Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/component_energy_area.ipynb Creates a global buffer component from a YAML file, calculates its area, energy, leak power, and throughput, then prints the results. Uses the `calculate_component_costs` method. ```python # < DOC_INCLUDE_MARKER > single_component_energy_area # Create the component from the yaml file import accelforge as af global_buffer = af.arch.Memory.from_yaml( examples_dir / "misc" / "component_annotated.yaml" ) # Calculate the energy and area of the component global_buffer = global_buffer.calculate_component_costs() # Print out the area, leak power, and energy for each action area = global_buffer.area leak_power = global_buffer.leak_power print(f"Area: {area:.2e} m^2") print(f"Leak power: {leak_power:.2e} W") for action in global_buffer.actions: energy = action.energy throughput = action.throughput print( f"Action {action.name} energy {energy:.2e} J, throughput {throughput:.2e} actions/s" ) ``` -------------------------------- ### Print calculate_component_costs documentation Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/component_energy_area.ipynb Prints the docstring of the `calculate_component_costs` method to inspect available attributes and behavior. ```python print(global_buffer.calculate_component_costs.__doc__) ``` -------------------------------- ### Initialize Spec and Map Workload for Orojenesis Source: https://github.com/accelergy-project/accelforge/blob/main/notebooks/tutorials/memory_size_vs_access_tradeoff.ipynb Initializes an AccelForge Spec with the snowcat architecture and a 4096x4096x4096 matrix multiply workload, sets mapper metrics to ENERGY and RESOURCE_USAGE, and maps the workload to the architecture. ```python import accelforge as af from pathlib import Path examples_dir = Path("../../examples") spec = af.Spec.from_yaml( af.examples.arches.snowcat, af.examples.workloads.basic.matmuls, jinja_parse_data={"N_EINSUMS": 1, "M": 4096, "KN": 4096}, ) spec.mapper.metrics = af.Metrics.ENERGY | af.Metrics.RESOURCE_USAGE results = spec.map_workload_to_arch() ``` -------------------------------- ### join_pmappings Source: https://github.com/accelergy-project/accelforge/blob/main/docs/source/guide/modeling/mapping.rst Join all Pareto-optimal pmappings for all Einsums into full mappings. Returns a Mappings object containing all Pareto-optimal mappings found for the given cascade of Einsums. ```APIDOC ## join_pmappings ### Description Join all Pareto-optimal pmappings for all Einsums into full mappings. Returns a Mappings object containing all Pareto-optimal mappings found for the given cascade of Einsums. ### Returns - **Mappings** - An object containing all Pareto-optimal mappings found for the given cascade of Einsums. ### Errors - Raises an error if there are no valid mappings to join, reporting the compatibilities of the pmappings that were considered. ```