Compare commits
2 Commits
main
..
942a9faa4f
| Author | SHA1 | Date | |
|---|---|---|---|
| 942a9faa4f | |||
| 893e90feac |
@@ -1,43 +0,0 @@
|
||||
# pimsim-nn Oracle Invariant
|
||||
|
||||
`backend-simulators/pim/pimsim-nn` is the performance oracle. Its simulation
|
||||
behavior defines the hardware model used for Raptor/PIMCOMP comparisons.
|
||||
|
||||
## Required invariant
|
||||
|
||||
- Do not add instruction or operator support to pimsim-nn.
|
||||
- Changes to pimsim-nn must preserve simulation behavior exactly. Acceptable
|
||||
changes are limited to behavior-neutral maintenance proven not to alter
|
||||
simulated timing, scheduling, power, energy, or supported input programs.
|
||||
- Other unsupported or unknown pimsim-nn operations remain unsupported. Do not
|
||||
approximate their timing or map them onto another operation.
|
||||
- Validation must report an explicit unsupported-op diagnostic as
|
||||
`UNSUPPORTED`, not as a simulator failure.
|
||||
- A compiled artifact with zero active PIM cores has no meaningful
|
||||
non-functional simulation and must be reported as `SKIP`.
|
||||
|
||||
## Explicit `vsoftmax` exception
|
||||
|
||||
`vsoftmax` has no Pimsim-nn hardware timing model. This one explicitly
|
||||
authorized exception does not permit other simulator approximations.
|
||||
|
||||
- Pimsim-nn omits `vsoftmax` while loading JSON or binary instructions, before
|
||||
fetch. Omitted instructions consume no fetch, issue, execution, memory, or
|
||||
dynamic-energy service.
|
||||
- Pimsim-nn warns once per process that Softmax timing and energy are excluded.
|
||||
- Functional simulation executes Softmax normally.
|
||||
- Raptor's queue estimator applies the same zero-cost omission. All surrounding
|
||||
instructions, materialization, transfers, and synchronization remain modeled.
|
||||
- `state.instructions` intentionally counts `vsoftmax`: it is a real encoded
|
||||
PIM instruction, although Pimsim-nn does not simulate it.
|
||||
- No additional Pimsim-nn behavior changes are authorized.
|
||||
|
||||
Current comparisons use the full YOLO11n model, including both Softmax
|
||||
operations, at `validation/networks/yolo11n/depth_51/yolo11n_depth_51.onnx`.
|
||||
GoogLeNet uses
|
||||
`validation/networks/pimcomp_models/googlenet/googlenet-12-no-lrn.onnx`,
|
||||
with only its two unsupported LRN nodes bypassed. Terminal Softmax is retained.
|
||||
Historical Softmax-free artifacts are not matched baselines for these graphs.
|
||||
|
||||
Any proposed pimsim-nn behavior change requires explicit user authorization and
|
||||
must not be introduced as part of a compiler optimization.
|
||||
@@ -1,105 +0,0 @@
|
||||
# PIM Synchronization Invariant
|
||||
|
||||
## Scope
|
||||
|
||||
This invariant applies to PIM `SYNC`/`WAIT` planning, event-register
|
||||
allocation, repeating core bodies, host/global-memory transfers, and pipeline
|
||||
restart synchronization.
|
||||
|
||||
## ISA contract
|
||||
|
||||
`SYNC event, target` and `WAIT event, expected` have static operands. Event
|
||||
registers start at zero, persist across instruction-stream restart, and are
|
||||
incremented by `SYNC`. `WAIT` succeeds only when the register equals its
|
||||
static expected count, then resets it to zero. A plan must therefore guarantee
|
||||
exactly the expected number of increments before each wait. It must not use
|
||||
generation-dependent registers, treat `WAIT` as `>=`, permit overshoot, or
|
||||
consume one event register with independent waits in the same iteration.
|
||||
|
||||
Event registers are local to the target core. Allocation must keep READY,
|
||||
FREE/reuse, stage-zero barrier, and downstream restart events disjoint on each
|
||||
physical core.
|
||||
|
||||
## Host/global-memory lifetime
|
||||
|
||||
For every host-routed dependency from writer `W` to reader `R`, the repeating
|
||||
program must establish:
|
||||
|
||||
```text
|
||||
ST_N -> READY SYNC -> READY WAIT -> LD_N
|
||||
LD_N -> reader END_N -> reader start_N+1 -> FREE SYNC
|
||||
-> writer FREE WAIT -> ST_N+1
|
||||
```
|
||||
|
||||
The reader emits one FREE `SYNC` per unique physical `(W, R)` relation at body
|
||||
entry, before any instruction that can block. The writer consumes each FREE
|
||||
event at most once per iteration, with a static count equal to the unique
|
||||
readers in that reuse group. The wait is placed immediately before the first
|
||||
host store that can overwrite a member of the group, after all preceding
|
||||
useful computation. Multiple transfers on one `(W, R)` relation do not create
|
||||
additional FREE signals.
|
||||
|
||||
Relations with the same writer and first dangerous overwrite boundary belong
|
||||
to one FREE group: splitting them cannot unblock an earlier store and only
|
||||
adds waits and register pressure. After preserving the READY registers required
|
||||
by a core, planning assigns independent groups to distinct overwrite boundaries
|
||||
as remaining capacity permits. Capacity-forced merged groups are ordered by
|
||||
first overwrite and waited before their earliest member. Unused READY capacity
|
||||
must not force all readers into one early aggregate wait.
|
||||
|
||||
Host receives lower to READY `WAIT` followed by host load only. They must not
|
||||
emit a post-load acknowledgement. Writers must not wait for host readers at
|
||||
the end of their body. The repeated reader-entry FREE signal is both the
|
||||
initial-slot bootstrap and the release of the previous generation.
|
||||
|
||||
## Pipeline restart independence
|
||||
|
||||
Host lifetime synchronization does not replace pipeline restart
|
||||
synchronization. At the end of every repeating stage-zero body, all unique
|
||||
stage-zero physical cores execute a dissemination barrier with
|
||||
`ceil(log2(stageZeroCoreCount))` rounds. In round `r`, rank `i` sends one
|
||||
signal to rank `(i + 2^r) mod count` and waits for exactly one signal on that
|
||||
round's destination-local event register. Each round has its own register, so
|
||||
an early signal for a later round cannot overshoot or satisfy another wait.
|
||||
|
||||
Every downstream core sends one restart-permission signal to its release-tree
|
||||
parent at body entry, after all host FREE signals. The root signals the
|
||||
stage-zero leader; other cores signal their binary-tree parent. After the barrier, the lowest-ranked
|
||||
stage-zero core waits for the root's permission before sending one restart
|
||||
signal to it. Every downstream parent waits for exactly one restart signal
|
||||
and for one permission from each existing child before forwarding the restart
|
||||
to those children and ending its current body. This reverse permission path
|
||||
prevents a fast parent from sending generation `N+1` before a child consumes
|
||||
generation `N`, which would overshoot an exact-count restart event.
|
||||
|
||||
Thus no downstream core can restart and advance its input generation until
|
||||
every stage-zero core has completed the protected generation, and every
|
||||
restart event receives exactly one signal between waits. Stage-zero and
|
||||
downstream core sets are disjoint; barrier, restart, and restart-permission
|
||||
registers are reserved on their respective target cores. Host READY/FREE
|
||||
allocation must use only the remaining registers and must not move, merge,
|
||||
remove, or weaken this ordering.
|
||||
|
||||
## Ownership and verification
|
||||
|
||||
Deferred boundary planning owns relation deduplication, event allocation,
|
||||
expected counts, and the first dangerous overwrite action. Boundary
|
||||
realization owns body-entry FREE signals and materializes planned waits at
|
||||
their exact boundaries. Channel lowering preserves those explicit operations
|
||||
and lowers host receives as READY wait plus load; it must not reconstruct
|
||||
lifetime policy after scheduling information is lost.
|
||||
|
||||
Verification must reject non-static lane/core mappings, duplicate physical
|
||||
reader representations, register collisions, oversubscribed event capacity,
|
||||
and any plan whose generated FREE signal count differs from its static wait
|
||||
count. Static and simulator deadlock detectors must model blocking WAITs,
|
||||
their remaining matching SYNC producers, missing signals, and exact-count
|
||||
overshoot in addition to SEND/RECV cycles. Both detectors must retain the
|
||||
per-source contributions accumulated since the last successful WAIT and must not
|
||||
add a wait-for edge to a source that already supplied its share of the current
|
||||
event value merely because that source has the same static SYNC in a future
|
||||
iteration. Structural tests must inspect generated instruction streams. Happens-
|
||||
before tests must unroll at least two logical iterations and add only
|
||||
same-core restart edges plus matched communication edges. Functional
|
||||
simulation must enforce exact-count waits and include stalled or randomized
|
||||
legal schedules so correctness never depends on relative core speed.
|
||||
@@ -1,70 +0,0 @@
|
||||
# Pipeline Scheduling Invariant
|
||||
|
||||
## Scope
|
||||
|
||||
This invariant applies to pipeline stage partitioning, physical-core
|
||||
assignment, scheduled materialization, deferred transfers, and pipeline
|
||||
synchronization.
|
||||
|
||||
## Invariant
|
||||
|
||||
`--pipeline=1` preserves latency-oriented PEFT and remains the default.
|
||||
An explicit `--pipeline=N`, with `N > 1`, requires exactly `N` nonempty
|
||||
compute stages, identified by all integers from zero through `N - 1`.
|
||||
Each stage owns at least one physical core and scheduled compute work.
|
||||
Initialization, feasibility completion, refinement, allocation, placement,
|
||||
and final verification must preserve this count. Fixed-depth refinement
|
||||
must not remove stages or compact the schedule to a smaller depth.
|
||||
An unsupported exact depth fails explicitly; empty stages are not a repair.
|
||||
`--pipeline=auto` permits depth changes within the legal resource domain.
|
||||
It compares PEFT p1 and pipeline schedules using steady-state queue costs.
|
||||
Auto p1 preserves PEFT placement and uses the existing stage-zero restart
|
||||
barrier for repeated inputs. Numeric p1 remains the latency program.
|
||||
|
||||
A scheduled compute operation and all of its lanes belong to exactly one
|
||||
pipeline stage. An operation may consume results produced in its own stage or
|
||||
the immediately preceding stage only. Therefore every compute-graph edge from
|
||||
stage `S` targets stage `S` or `S + 1`; backward edges and dependencies that
|
||||
skip a stage are invalid.
|
||||
|
||||
Dynamic function inputs are stage-zero sources. Any operation that directly
|
||||
consumes one must belong to stage 0. A later stage may consume that data only
|
||||
through an explicit result forwarded by the preceding stage.
|
||||
|
||||
PEFT assigns physical cores using the injected target topology and their actual
|
||||
resident-weight capacity. Pipeline stage capacities cover every physical core
|
||||
and may have different sizes when the partitioner predicts a lower maximum
|
||||
stage interval. Before stage-local packing, the layout groups physical cores
|
||||
by bidirectional link cost; stage cores need not have consecutive IDs. Packing
|
||||
scores transfers on those physical links, and communication realization must
|
||||
preserve the resulting core identities.
|
||||
Synchronization and deferred transfers consume the explicit stage identity;
|
||||
they must not infer it from a physical core number after placement.
|
||||
|
||||
## Ownership
|
||||
|
||||
Latency PEFT and pipeline scheduling independently consume the shared compute
|
||||
graph and target cost model. Stage partitioning is the first phase of pipeline
|
||||
scheduling and owns stage adjacency. It must construct a valid
|
||||
operation-level partition before physical-core packing. Operations split for
|
||||
physical capacity retain one shared stage identity. Repacking may move work
|
||||
only within its assigned stage. Deferred-transfer planning and
|
||||
synchronization consume the verified stage assignment; they must not repair
|
||||
or reinterpret it.
|
||||
|
||||
## Verification
|
||||
|
||||
Before scheduled materialization, verify that:
|
||||
|
||||
- every compute instance has one valid physical core and stage;
|
||||
- all lanes of one compute operation have the same stage;
|
||||
- every direct dynamic-function-input consumer belongs to stage 0;
|
||||
- every compute-graph edge stays within a stage or advances exactly one stage;
|
||||
- every stage-local resident-weight set fits its assigned physical core; and
|
||||
- stage capacities cover all physical cores exactly once; and
|
||||
- physical placement is a permutation of all target cores.
|
||||
|
||||
Pipeline scheduling tests must include an uneven physical-core layout and a
|
||||
graph with a long-lived dependency that would cross multiple naive stage
|
||||
cuts. End-to-end validation must preserve functional results and exercise the
|
||||
existing synchronization lowering without simulator changes.
|
||||
@@ -26,11 +26,6 @@ jobs:
|
||||
https://chef.heaplab.deib.polimi.it/git/${GITHUB_REPOSITORY}.git \
|
||||
${GITHUB_WORKSPACE}
|
||||
|
||||
- name: Check dialect reference
|
||||
run: |
|
||||
python3 docs/dialects/check_reference.py
|
||||
python3 -m unittest discover -s docs/dialects -p 'test_*.py'
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt update
|
||||
|
||||
@@ -1,29 +1,11 @@
|
||||
* Always read the full README.md before doing anything
|
||||
|
||||
# Communication: ASD-STE100
|
||||
|
||||
* Use ASD-STE100 Simplified Technical English (STE) for all user-facing English prose.
|
||||
* Apply this rule to plans, progress updates, questions, explanations, code reviews, and final responses.
|
||||
* Use approved STE words with their approved meanings and parts of speech, as far as the available standard permits.
|
||||
* Use consistent technical terms when approved general words cannot express an engineering concept accurately.
|
||||
* Use short, direct sentences. Use active voice in procedures and one instruction per sentence.
|
||||
* Keep procedural sentences to 20 words or fewer and descriptive sentences to 25 words or fewer.
|
||||
* Avoid idioms, slang, unnecessary words, and ambiguous expressions.
|
||||
* Before sending a response, check its prose against these rules and correct identifiable violations.
|
||||
* Preserve technical accuracy if an STE restriction would change the meaning.
|
||||
* Do not alter source code, identifiers, APIs, commands, file paths, logs, or quoted text to satisfy STE.
|
||||
* Do not rewrite existing documentation or code comments solely to satisfy STE. Apply STE to new prose when practical.
|
||||
* Do not claim verified ASD-STE100 compliance without independent validation against the official standard.
|
||||
|
||||
# Required project invariants
|
||||
|
||||
Before modifying the relevant subsystem, read:
|
||||
|
||||
* `.agents/invariants/GRAPH_COMPUTE_BATCH_INVARIANT.md`
|
||||
* `.agents/invariants/PERFORMANCE_OPTIMIZATION_INVARIANT.md`
|
||||
* `.agents/invariants/PIMSIM_NN_ORACLE_INVARIANT.md`
|
||||
* `.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md`
|
||||
* `.agents/invariants/PIPELINE_SCHEDULING_INVARIANT.md`
|
||||
* `.agents/invariants/SPATIAL_TARGET_GENERALITY_INVARIANT.md`
|
||||
* Build commands:
|
||||
* `cmake --build ./build_release`
|
||||
@@ -168,32 +150,6 @@ Do not refactor when:
|
||||
* When your changes create orphans, remove imports, variables, functions, or files made unused by your change
|
||||
* Every changed line should trace directly to the requested fix, a required cleanup, or a justified reuse/refactor decision
|
||||
|
||||
# Documentation
|
||||
|
||||
* Keep `docs/dialects/index.html` current when operations, assembly, verifiers,
|
||||
lowering, bufferization, or codegen contracts change. Update the same change.
|
||||
* Each entry must describe the exact printed mnemonic and syntax, input/output
|
||||
roles and shapes, attributes and units, semantics, and constraints. Distinguish
|
||||
enforced checks from producer assumptions and backend limits. Read the relevant
|
||||
implementation, not only the TableGen summary. Preserve the offline HTML format.
|
||||
* State what every structural dimension and identifier counts. Distinguish SSA
|
||||
values and fragment slots from logical model axes, memory allocation, and core
|
||||
placement. For graph batches, follow the graph fragment invariant explicitly.
|
||||
Do not assume input tensors have a leading lane dimension. Shared bindings
|
||||
describe SSA reuse; they do not guarantee shared physical storage.
|
||||
Trace input producers and layout descriptors. Inputs can use logical coordinates
|
||||
or fragment slots; a logical tensor type does not guarantee dense storage.
|
||||
* Run `.venv/bin/python docs/dialects/check_reference.py` and
|
||||
`.venv/bin/python -m unittest discover -s docs/dialects -p 'test_*.py'`.
|
||||
For syntax changes, parse and print affected examples with the current
|
||||
`onnx-mlir-opt --maccel=PIM` build in their required region/weight context.
|
||||
* Keep `docs/lowering-visuals/im2col-story` current when convolution, GEMM,
|
||||
graph publication, or scheduling contracts change. Update the generator,
|
||||
regenerate SVGs, and run `node docs/lowering-visuals/im2col-story/book.test.js`.
|
||||
|
||||
* Do not create or retain agent change reports, investigation logs, debugging histories, temporary benchmark audits, or task-completion summaries in repository documentation. Report these findings in the final response instead.
|
||||
* Documentation should describe the current system, its contracts, usage, and reproducible methodology. Document lasting limitations where relevant, without narrating how they were discovered or fixed.
|
||||
|
||||
# Diagnostics and verification
|
||||
|
||||
* Use existing bounded diagnostic mechanisms for pass-level verification or codegen failures
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 HeapLab
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,64 +1,163 @@
|
||||
# Raptor
|
||||
|
||||
Raptor is an MLIR compiler for ONNX neural networks targeting processing-in-memory
|
||||
(PIM) architectures. It extends ONNX-MLIR and emits per-core `.pim` binaries,
|
||||
`memory.bin`, `config.json`, and weights for the simulators under
|
||||
`backend-simulators/pim/`. Optional JSON instructions use `--pim-emit-json`.
|
||||
Raptor is a domain-specific MLIR compiler for neural networks in ONNX format,
|
||||
targeting in-memory computing / processing-in-memory (PIM) architectures. It
|
||||
extends ONNX-MLIR with a PIM accelerator and progressively lowers ONNX-MLIR
|
||||
through custom MLIR dialects to simulator artifacts.
|
||||
|
||||
The target has shared host memory, PIM cores with ReRAM crossbars, explicit
|
||||
inter-core communication, and no hardware branches or loops. Lowering,
|
||||
scheduling, and memory planning keep repeated work compact until codegen.
|
||||
The current target is the PIM simulator stack under `backend-simulators/pim`.
|
||||
Raptor emits binary per-core `.pim` instruction files by default, plus
|
||||
`memory.bin`, `config.json`, and weight binaries. It can also emit per-core JSON
|
||||
instruction files with `--pim-emit-json`.
|
||||
|
||||
## Build
|
||||
## Overview
|
||||
|
||||
Initialize submodules:
|
||||
PIM architectures perform most computation directly in memory. The supported
|
||||
target models a chip with:
|
||||
- shared host memory,
|
||||
- multiple PIM cores,
|
||||
- ReRAM crossbars for vector-matrix / matrix-vector work,
|
||||
- explicit communication between cores,
|
||||
- no hardware branch or loop support in emitted simulator code.
|
||||
|
||||
```bash
|
||||
git submodule update --init --recursive
|
||||
Because repeated work such as convolutions is eventually made explicit, emitted
|
||||
instruction counts can grow quickly. Most compiler work therefore focuses on
|
||||
lowering, scheduling, memory layout, and code-generation optimizations.
|
||||
|
||||
### Targets and simulators
|
||||
|
||||
- `backend-simulators/pim/pim-simulator` is the in-tree Rust functional
|
||||
simulator used by validation. It reads Raptor's `pim/` artifact directory and
|
||||
compares simulator output against native ONNX-MLIR execution.
|
||||
- `backend-simulators/pim/pimsim-nn` is the non-functional simulator submodule
|
||||
used internally by validation for latency, power, and energy.
|
||||
The helper scripts in `pimcomp_utils/` are for comparison with PIMCOMP-NN and
|
||||
contain local paths; treat them as local utilities, not portable workflows.
|
||||
|
||||
## Compilation pipeline
|
||||
|
||||
The PIM sources live under `src/PIM` and tests under `test/PIM`. CMake exposes
|
||||
them to ONNX-MLIR through generated shim directories under
|
||||
`onnx-mlir/src/Accelerators/PIM` and `onnx-mlir/test/accelerators/PIM`.
|
||||
|
||||
High-level lowering flow:
|
||||
|
||||
```
|
||||
ONNX-MLIR -> Spatial -> Pim (tensor) -> Pim (bufferized) -> PIM artifacts
|
||||
```
|
||||
|
||||
Follow [ONNX-MLIR's LLVM/MLIR build instructions](onnx-mlir/docs/BuildOnLinuxOSX.md).
|
||||
The [CI workflow](.github/workflows/validate_operations.yml) records dependency
|
||||
versions and setup, including CMake and Protobuf. Rust stable is required for
|
||||
the functional simulator. Python requirements include the Graph Explorer and
|
||||
need Python 3.13+; create the repository environment if absent, then install:
|
||||
1. **ONNX -> Spatial** (`src/PIM/Conversion/ONNXToSpatial`).
|
||||
Lowers supported ONNX ops into the `spat` dialect
|
||||
(`src/PIM/Dialect/Spatial`). Conversion patterns are split by op family under
|
||||
`Patterns/{Math,NN,Tensor}` and currently cover Conv, Gemm, MatMul,
|
||||
elementwise Add/Mul/Div, ReduceMean, pooling, Relu, Sigmoid, Softmax,
|
||||
Concat, Gather, Reshape, Resize, and Split.
|
||||
The compiler-layer target adapter supplies the target-neutral
|
||||
`SpatialTargetInfo`. Layout-aware plan ops advertise typed alternatives
|
||||
through the Spatial layout interface; the layout planner records the
|
||||
selected layout and explicit materialization edges. `LowerSpatialPlans`
|
||||
then pattern-lowers those selected plans. Contraction and Conv lowering
|
||||
keep semantic problems, target-dependent plans, and IR materializers in
|
||||
separate layers.
|
||||
|
||||
```bash
|
||||
python3.13 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements.txt
|
||||
```
|
||||
2. **Merge, schedule, and realize Spatial communication**
|
||||
(`src/PIM/Dialect/Spatial/Transforms/MergeComputeNodes`).
|
||||
`TrivialGraphComputeMerge` performs local graph merging, then
|
||||
`ScheduleSpatialGraph` materializes scheduled computes and explicit deferred
|
||||
communication. `VerifyScheduledSpatial` checks that intermediate contract;
|
||||
`RealizeSpatialCommunication` resolves transfers and forwarding; and
|
||||
`VerifyRealizedSpatial` checks the final scheduled graph. Supporting
|
||||
scheduling code lives under `MergeComputeNodes/Scheduling`.
|
||||
|
||||
If compatible Protobuf libraries are unavailable locally:
|
||||
3. **Spatial -> Pim** (`src/PIM/Conversion/SpatialToPim`).
|
||||
Lowers Spatial operations to the `pim` dialect (`src/PIM/Dialect/Pim`),
|
||||
including `pim.core`, `pim.core_batch`, communication, tensor packing, global
|
||||
tensor materialization, and return-path normalization.
|
||||
|
||||
```bash
|
||||
git clone --depth 1 --branch v34.0 https://github.com/protocolbuffers/protobuf
|
||||
cmake -S protobuf -B protobuf/build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -Dprotobuf_BUILD_TESTS=OFF
|
||||
cmake --build protobuf/build
|
||||
sudo cmake --install protobuf/build
|
||||
```
|
||||
4. **Bufferization** (`src/PIM/Dialect/Pim/Transforms/Bufferization`).
|
||||
`PimBufferizationPreparation` establishes writable destinations without
|
||||
duplicating the one-shot copy analysis, `PimOneShotBufferization` runs
|
||||
MLIR's one-shot analysis,
|
||||
`PimMemoryNormalization` forwards/removes redundant copies and normalizes
|
||||
addressable accesses, and `PimBufferizationVerification` checks tensor
|
||||
absence, contiguity, and copy address spaces.
|
||||
|
||||
Configure and build Raptor, adjusting `MLIR_DIR` to your LLVM build:
|
||||
5. **PIM local-memory planning**
|
||||
(`src/PIM/Dialect/Pim/Transforms/LocalMemoryPlanning`).
|
||||
Computes whole-core lifetimes, reuses addresses for non-overlapping
|
||||
allocations, and records the explicit plan in PIM IR.
|
||||
6. **PIM verification and code generation** (`src/PIM/Pass/PimCodegen` and
|
||||
`src/PIM/Compiler`).
|
||||
Verifies the memory plan and other PIM invariants, then emits `.pim` core
|
||||
files, weights, and `memory.bin` / `config.json` without rerunning liveness.
|
||||
|
||||
```bash
|
||||
cmake -S . -B build_release -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DONNX_MLIR_ACCELERATORS=PIM \
|
||||
-DLLVM_ENABLE_ASSERTIONS=ON \
|
||||
-DMLIR_DIR="$PWD/onnx-mlir/llvm-project/build_release/lib/cmake/mlir"
|
||||
cmake --build ./build_release
|
||||
```
|
||||
Supporting pieces:
|
||||
- `src/PIM/Common` - shared IR, filesystem, diagnostics, reports, and utility
|
||||
helpers.
|
||||
- `src/PIM/Compiler` - PIM compiler options, planned-address materialization, binary
|
||||
instruction format, artifact writing, weight emission, and codegen entry
|
||||
points.
|
||||
- `src/PIM/Conversion/SpatialToGraphviz` - optional Spatial graphviz conversion
|
||||
pass.
|
||||
- `src/PIM/Pass` - pass registration and auxiliary passes.
|
||||
- `src/PIM/PimAccelerator.{cpp,hpp}` - ONNX-MLIR accelerator entry point.
|
||||
|
||||
Use release builds first. For debugging, configure `build_debug` with
|
||||
`-DCMAKE_BUILD_TYPE=Debug` and the matching MLIR package, then run
|
||||
`cmake --build ./build_debug`. Use debug only for small cases requiring symbols.
|
||||
Optional `mold` linking uses `-fuse-ld=mold` in
|
||||
`CMAKE_{EXE,SHARED,MODULE}_LINKER_FLAGS`.
|
||||
## PIM compiler options
|
||||
|
||||
Always build through `cmake --build`; invoking `ninja` directly bypasses CMake
|
||||
configuration and generated shim updates.
|
||||
Pass these to `onnx-mlir` when compiling for PIM. These are all Raptor/PIM-specific
|
||||
options; `onnx-mlir --help` lists the inherited ONNX-MLIR options.
|
||||
|
||||
## Compile a model
|
||||
- `--maccel=PIM` - select the PIM accelerator.
|
||||
- `--EmitSpatial`, `--EmitPim`, `--EmitPimBufferized`,
|
||||
`--EmitPimCodegen` - stop the PIM pipeline at the requested stage. The PIM
|
||||
default is `--EmitPimCodegen`.
|
||||
- `--core-count=<N>` - required positive core count for PIM compilation.
|
||||
- `--crossbar-size=<N>` - crossbar width/height. Default in code is `128`.
|
||||
- `--crossbar-count=<N>` - crossbars per core. Default in code is `64`.
|
||||
- `--pim-target-config=<PATH>` - optional PIM target configuration used by the
|
||||
target adapter to construct the target-neutral Spatial scheduling cost and
|
||||
topology model. Resource values must match the explicit core/crossbar flags.
|
||||
- `--pim-memory-report=<summary|none>` - emit the concise combined memory report
|
||||
under `reports/memory_report.txt`, or disable it. Default is `summary`.
|
||||
- `--pim-only-codegen` - assume input is already bufferized PIM IR and only run
|
||||
the codegen tail.
|
||||
- `--pim-emit-json` - also emit `core_*.json` instruction files alongside
|
||||
`core_*.pim`.
|
||||
- `--pim-export-spatial-dataflow=<none|spatial1|spatial2|spatial3|spatial4|all>` -
|
||||
control Spatial dataflow CSV reports for the graph, trivially merged graph,
|
||||
scheduled, and realized snapshots under `reports/`. Default is `none`.
|
||||
- `--pim-conv-lowering=<auto|legacy|depthwise|packed-im2col|streamed-patch|streamed-packed|output-channel-tiled|input-k-tiled|tiled-2d>` -
|
||||
select the convolution lowering strategy. Default is `auto`.
|
||||
- `--pim-conv-im2col-max-elements=<N>` - maximum globally materialized im2col
|
||||
elements per convolution before streaming. Default is `1048576`.
|
||||
- `--pim-conv-stream-chunk-positions=<N>` - maximum output positions per
|
||||
streamed convolution chunk. Default is `1024`.
|
||||
- `--use-experimental-conv-impl` - use the alternate convolution lowering.
|
||||
- `--pim-detect-communication-deadlock` - statically simulate expanded
|
||||
send/receive ordering and reject blocking deadlocks. Default is off.
|
||||
- `--pim-materialize-scalar-fanout-global-order` - use the experimental,
|
||||
expensive globally ordered scalar-fanout materializer. Default is off.
|
||||
- `--pim-trace-communication-materialization` - emit verbose communication
|
||||
materialization diagnostics and provenance attributes. Default is off.
|
||||
- `--ignore-concat-error` - soft-fail a ConcatOp corner case.
|
||||
|
||||
## Standard PIM hardware profile
|
||||
|
||||
Raptor's standard development and YOLO validation profile is:
|
||||
|
||||
| Parameter | Value |
|
||||
| --- | ---: |
|
||||
| Cores | 144 |
|
||||
| Crossbars per core | 64 |
|
||||
| Crossbar size | 128 × 128 |
|
||||
|
||||
Canonical compiler flags:
|
||||
|
||||
`--crossbar-count=64 --crossbar-size=128 --core-count=144`
|
||||
|
||||
`--core-count` remains mandatory and must be passed explicitly to the compiler.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
./build_release/Release/bin/onnx-mlir model.onnx -o /tmp/raptor/model \
|
||||
@@ -66,25 +165,131 @@ configuration and generated shim updates.
|
||||
--crossbar-count=64 --crossbar-size=128 --core-count=144
|
||||
```
|
||||
|
||||
This writes artifacts under `/tmp/raptor/pim/`. All three hardware flags are
|
||||
mandatory positive values. The example uses the development/YOLO profile;
|
||||
[Pimcomp comparison profiles](validation/networks/pimcomp_models/README.md#hardware-profiles)
|
||||
differ, and validation defaults to Arch-A.
|
||||
This writes PIM artifacts under `/tmp/raptor/pim/`.
|
||||
|
||||
## Documentation
|
||||
## Validation
|
||||
|
||||
Open the [dialect operation reference](docs/dialects/index.html) in a browser.
|
||||
It describes each operation's printed syntax, inputs, outputs, semantics, and constraints.
|
||||
Functional validation compiles ONNX models, compares native ONNX-MLIR and PIM
|
||||
simulator outputs, and optionally reports latency, power, and energy. See
|
||||
[`validation/README.md`](validation/README.md) for prerequisites, usage,
|
||||
options, artifacts, and results.
|
||||
|
||||
The [paper artifact](artifact/README.md) builds the pinned compiler and simulators
|
||||
in Docker, runs the comparison and ablation experiments, and generates plots.
|
||||
## Build
|
||||
|
||||
Start with the [documentation index](docs/README.md). It links the
|
||||
[compiler architecture](docs/compiler/architecture.md),
|
||||
[compiler options](docs/compiler/options.md), and
|
||||
[evaluation methodology](docs/evaluation/methodology.md).
|
||||
Initialize submodules first:
|
||||
|
||||
[Validation commands](validation/README.md), the
|
||||
[operation inventory](validation/operations/INVENTORY.md), and the
|
||||
[Graph Explorer](tools/raptor_graph_explorer/README.md) remain beside their
|
||||
components.
|
||||
```bash
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
The project follows ONNX-MLIR's build requirements. The CI workflow documents
|
||||
the currently used versions and setup:
|
||||
- CMake 4.3.0 in CI,
|
||||
- LLVM/MLIR checked out under `onnx-mlir/llvm-project`,
|
||||
- Protobuf `v34.0`,
|
||||
- Rust stable for `pim-simulator`,
|
||||
- Python packages `numpy`, `onnx`, `colorama` for validation.
|
||||
|
||||
### Protobuf
|
||||
|
||||
Install Protobuf if your system does not already provide a compatible version:
|
||||
|
||||
```bash
|
||||
git clone --depth 1 --branch v34.0 https://github.com/protocolbuffers/protobuf
|
||||
cmake -S protobuf -B protobuf/build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-Dprotobuf_BUILD_TESTS=OFF
|
||||
cmake --build protobuf/build
|
||||
sudo cmake --install protobuf/build
|
||||
```
|
||||
|
||||
You can then remove the temporary checkout:
|
||||
|
||||
```bash
|
||||
rm -rf protobuf
|
||||
```
|
||||
|
||||
### MLIR
|
||||
|
||||
Follow the ONNX-MLIR instructions in
|
||||
`onnx-mlir/docs/BuildOnLinuxOSX.md` to build LLVM/MLIR. The local Raptor build
|
||||
expects `MLIR_DIR` to point at the MLIR CMake package, for example:
|
||||
|
||||
```bash
|
||||
MLIR_DIR=$(pwd)/onnx-mlir/llvm-project/build_release/lib/cmake/mlir
|
||||
```
|
||||
|
||||
If your LLVM build directory is named `build` instead of `build_release`, adjust
|
||||
the path accordingly.
|
||||
|
||||
### Raptor
|
||||
|
||||
Configure a release build:
|
||||
|
||||
```bash
|
||||
MLIR_DIR=$(pwd)/onnx-mlir/llvm-project/build_release/lib/cmake/mlir
|
||||
cmake -S . -B build_release -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DONNX_MLIR_ACCELERATORS=PIM \
|
||||
-DLLVM_ENABLE_ASSERTIONS=ON \
|
||||
-DMLIR_DIR=${MLIR_DIR}
|
||||
```
|
||||
|
||||
Configure a debug build similarly:
|
||||
|
||||
```bash
|
||||
MLIR_DIR=$(pwd)/onnx-mlir/llvm-project/build_debug/lib/cmake/mlir
|
||||
cmake -S . -B build_debug -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DONNX_MLIR_ACCELERATORS=PIM \
|
||||
-DLLVM_ENABLE_ASSERTIONS=ON \
|
||||
-DMLIR_DIR=${MLIR_DIR}
|
||||
```
|
||||
|
||||
For debug development, using `mold` can reduce link time and memory use:
|
||||
|
||||
```bash
|
||||
cmake -S . -B build_debug -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DONNX_MLIR_ACCELERATORS=PIM \
|
||||
-DLLVM_ENABLE_ASSERTIONS=ON \
|
||||
-DMLIR_DIR=${MLIR_DIR} \
|
||||
-DCMAKE_EXE_LINKER_FLAGS="-fuse-ld=mold" \
|
||||
-DCMAKE_SHARED_LINKER_FLAGS="-fuse-ld=mold" \
|
||||
-DCMAKE_MODULE_LINKER_FLAGS="-fuse-ld=mold"
|
||||
```
|
||||
|
||||
Build the compiler with CMake:
|
||||
|
||||
```bash
|
||||
cmake --build ./build_release
|
||||
cmake --build ./build_debug
|
||||
```
|
||||
|
||||
Do not invoke `ninja` directly for this project; use `cmake --build` so CMake's
|
||||
configuration and generated shims stay consistent.
|
||||
|
||||
If a build fails because Protobuf headers are missing fixed-width integer
|
||||
definitions, patch the affected Protobuf-generated files by adding
|
||||
`#include <cstdint>`.
|
||||
|
||||
## Tests
|
||||
|
||||
The Rust simulator has its own tests:
|
||||
|
||||
```bash
|
||||
cd backend-simulators/pim/pim-simulator
|
||||
cargo test
|
||||
```
|
||||
|
||||
## Repository Layout
|
||||
|
||||
- `src/PIM/` - PIM accelerator implementation.
|
||||
- `test/PIM/` - PIM C++ unit tests.
|
||||
- `validation/` - functional validation scripts, ONNX operation tests, network
|
||||
slices, and pimsim config generation.
|
||||
- `backend-simulators/pim/pim-simulator/` - in-tree Rust functional simulator.
|
||||
- `backend-simulators/pim/pimsim-nn/` - non-functional simulator submodule.
|
||||
- `pimcomp_utils/` - local comparison helpers for PIMCOMP-NN.
|
||||
- `.github/actions/` and `.github/workflows/validate_operations.yml` - CI setup
|
||||
for MLIR/Protobuf caching, building Raptor, and validation.
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
*
|
||||
!Dockerfile
|
||||
!pins.env
|
||||
!requirements.lock
|
||||
!models.sha256
|
||||
!build.sh
|
||||
!run.py
|
||||
!plot_ablation.py
|
||||
!source.tar.gz
|
||||
!source.sha256
|
||||
!validation-overlay/
|
||||
!validation-overlay/**
|
||||
!validation-overlay.sha256
|
||||
@@ -1,7 +0,0 @@
|
||||
/source.tar.gz
|
||||
/source.tar.gz.tmp
|
||||
/source.sha256
|
||||
/dist/
|
||||
/results/
|
||||
/validation-overlay/
|
||||
/validation-overlay.sha256
|
||||
@@ -1,46 +0,0 @@
|
||||
FROM python:3.12.12-slim-trixie AS python-deps
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
CC=clang-19 CXX=clang++-19 \
|
||||
LDFLAGS=-fuse-ld=mold \
|
||||
RUSTFLAGS="-C linker=clang-19 -C link-arg=-fuse-ld=mold" \
|
||||
CARGO_HOME=/opt/cargo RUSTUP_HOME=/opt/rustup \
|
||||
PATH=/opt/raptor/.venv/bin:/opt/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
|
||||
OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MPLBACKEND=Agg \
|
||||
PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 \
|
||||
HOME=/tmp XDG_CACHE_HOME=/tmp/cache MPLCONFIGDIR=/tmp/matplotlib
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential ca-certificates clang-19 curl git libomp-19-dev \
|
||||
libzstd-dev mold ninja-build pkg-config zlib1g-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /opt/artifact
|
||||
COPY pins.env requirements.lock models.sha256 build.sh ./
|
||||
RUN python -m venv /opt/raptor/.venv \
|
||||
&& /opt/raptor/.venv/bin/python -m pip install --no-cache-dir --only-binary=onnx -r requirements.lock
|
||||
|
||||
FROM python-deps AS artifact
|
||||
ARG BUILD_JOBS
|
||||
RUN . ./pins.env && curl --proto '=https' --tlsv1.2 -fsSL https://sh.rustup.rs -o /tmp/rustup.sh \
|
||||
&& sh /tmp/rustup.sh -y --profile minimal --default-toolchain "$RUST_VERSION" \
|
||||
&& rm /tmp/rustup.sh
|
||||
|
||||
COPY source.tar.gz source.sha256 ./
|
||||
RUN sha256sum -c source.sha256 \
|
||||
&& . ./pins.env \
|
||||
&& gzip -dc source.tar.gz > /tmp/raptor-source.tar \
|
||||
&& test "$(git get-tar-commit-id < /tmp/raptor-source.tar)" = "$RAPTOR_COMMIT" \
|
||||
&& tar -xf /tmp/raptor-source.tar -C /opt/raptor \
|
||||
&& rm source.tar.gz /tmp/raptor-source.tar
|
||||
RUN bash build.sh "${BUILD_JOBS:-$(env -u OMP_NUM_THREADS -u OMP_THREAD_LIMIT nproc)}"
|
||||
COPY validation-overlay/ ./validation-overlay/
|
||||
COPY validation-overlay.sha256 ./
|
||||
RUN sha256sum -c validation-overlay.sha256 \
|
||||
&& cp -R validation-overlay/validation/. /opt/raptor/validation/ \
|
||||
&& cp validation-overlay.sha256 /opt/artifact/provenance/
|
||||
COPY run.py plot_ablation.py ./
|
||||
|
||||
WORKDIR /opt/raptor
|
||||
ENTRYPOINT ["/opt/raptor/.venv/bin/python", "/opt/artifact/run.py"]
|
||||
CMD ["reproduce"]
|
||||
@@ -1,32 +0,0 @@
|
||||
# Raptor paper artifact
|
||||
|
||||
Raptor is fixed to commit `4a1fe710b2f0e4e9c0504f4fd9b4c4dd3df53b7d`.
|
||||
|
||||
Requires Docker on Linux or WSL2. The build downloads dependencies and uses Clang 19 and mold.
|
||||
Install the host dependencies:
|
||||
|
||||
```bash
|
||||
sudo apt install -y docker.io docker-cli docker-buildx git
|
||||
sudo systemctl enable --now docker
|
||||
sudo usermod -aG docker "$USER"
|
||||
newgrp docker
|
||||
```
|
||||
|
||||
Log out and back in, then run from this directory:
|
||||
|
||||
```bash
|
||||
bash artifact.sh build
|
||||
bash artifact.sh reproduce
|
||||
```
|
||||
|
||||
Open `results/full/index.html` to view the plots and result tables.
|
||||
The page also links to the CSV files and logs. Failed numerical validation remains visible in the results.
|
||||
|
||||
For a small VGG8 run, use `bash artifact.sh smoke` and open `results/smoke/index.html`.
|
||||
Build jobs, run jobs, and threads per job default to the available logical processor count.
|
||||
Override with `BUILD_JOBS`, `JOBS`, and `THREADS_PER_JOB`, or run `bash artifact.sh reproduce --jobs 8 --threads-per-job 4`.
|
||||
For another run, set `OUTPUT_DIR` to a new directory.
|
||||
|
||||
To prepare the paper attachment, run `bash artifact/artifact.sh package` from the repository root.
|
||||
The archive is written to `artifact/dist/` and includes the pinned sources and models.
|
||||
Updated scheduling code is included separately; compiler and simulator sources stay pinned.
|
||||
@@ -1,61 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
|
||||
source pins.env
|
||||
image="raptor-artifact:${RAPTOR_COMMIT:0:12}"
|
||||
command=${1:-help}
|
||||
if (($#)); then shift; fi
|
||||
case "$command" in
|
||||
prepare)
|
||||
exec bash prepare.sh
|
||||
;;
|
||||
package)
|
||||
bash prepare.sh
|
||||
mkdir -p dist
|
||||
archive="raptor-artifact-${RAPTOR_COMMIT:0:12}.tar.gz"
|
||||
package_dir=$(mktemp -d)
|
||||
trap 'rm -rf -- "$package_dir"' EXIT
|
||||
mkdir "$package_dir/raptor-artifact"
|
||||
cp \
|
||||
README.md artifact.sh prepare.sh Dockerfile .dockerignore pins.env \
|
||||
requirements.lock models.sha256 build.sh run.py plot_ablation.py source.tar.gz source.sha256 \
|
||||
"$package_dir/raptor-artifact/"
|
||||
cp -R validation-overlay "$package_dir/raptor-artifact/"
|
||||
cp validation-overlay.sha256 "$package_dir/raptor-artifact/"
|
||||
tar -czf "dist/$archive" -C "$package_dir" raptor-artifact
|
||||
(cd dist && sha256sum "$archive" > "$archive.sha256")
|
||||
printf 'Attachment: %s/dist/%s\n' "$PWD" "$archive"
|
||||
;;
|
||||
build)
|
||||
[[ -f source.tar.gz ]] || bash prepare.sh
|
||||
if [[ -f ../validation/raptor_validation/experiment_scheduler.py ]]; then
|
||||
bash prepare.sh --overlay-only
|
||||
fi
|
||||
sha256sum -c source.sha256
|
||||
docker build --build-arg "BUILD_JOBS=${BUILD_JOBS:-$(env -u OMP_NUM_THREADS -u OMP_THREAD_LIMIT nproc)}" -t "$image" .
|
||||
;;
|
||||
reproduce|smoke|plots)
|
||||
output=${OUTPUT_DIR:-"$PWD/results"}
|
||||
mkdir -p "$output"
|
||||
output=$(cd -- "$output" && pwd)
|
||||
image_id=$(docker image inspect --format '{{.Id}}' "$image")
|
||||
status=0
|
||||
docker run --rm --init --network none \
|
||||
--user "$(id -u):$(id -g)" \
|
||||
--env "ARTIFACT_IMAGE_ID=$image_id" \
|
||||
--env "JOBS=${JOBS:-$(env -u OMP_NUM_THREADS -u OMP_THREAD_LIMIT nproc)}" \
|
||||
--env "THREADS_PER_JOB=${THREADS_PER_JOB:-$(env -u OMP_NUM_THREADS -u OMP_THREAD_LIMIT nproc)}" \
|
||||
--mount "type=bind,src=$output,dst=/results" \
|
||||
"$image" "$command" "$@" || status=$?
|
||||
profile=full
|
||||
if [[ "$command" = smoke || " $* " = *' --smoke '* ]]; then profile=smoke; fi
|
||||
if [[ -f "$output/$profile/index.html" ]]; then
|
||||
printf '\nOpen %s/%s/index.html\n' "$output" "$profile"
|
||||
fi
|
||||
exit "$status"
|
||||
;;
|
||||
*)
|
||||
echo 'Usage: bash artifact.sh {build|smoke|reproduce|plots|package}'
|
||||
[[ "$command" = help ]]
|
||||
;;
|
||||
esac
|
||||
@@ -1,75 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
source /opt/artifact/pins.env
|
||||
export CMAKE_BUILD_PARALLEL_LEVEL=${1:-$(env -u OMP_NUM_THREADS -u OMP_THREAD_LIMIT nproc)}
|
||||
[[ "$CMAKE_BUILD_PARALLEL_LEVEL" =~ ^[1-9][0-9]*$ ]]
|
||||
cd /opt/raptor
|
||||
sha256sum -c /opt/artifact/models.sha256
|
||||
|
||||
checkout() {
|
||||
local url=$1 revision=$2 destination=$3
|
||||
git init "$destination"
|
||||
git -C "$destination" remote add origin "$url"
|
||||
git -C "$destination" fetch --depth 1 origin "$revision"
|
||||
git -C "$destination" checkout --detach FETCH_HEAD
|
||||
test "$(git -C "$destination" rev-parse HEAD)" = "$revision"
|
||||
git -C "$destination" submodule update --init --recursive --depth 1
|
||||
}
|
||||
|
||||
checkout https://github.com/onnx/onnx-mlir.git "$ONNX_MLIR_COMMIT" onnx-mlir
|
||||
checkout https://github.com/llvm/llvm-project.git "$LLVM_COMMIT" onnx-mlir/llvm-project
|
||||
checkout https://github.com/HEAPLab/PIMCOMP-NN.git "$PIMCOMP_COMMIT" third_party/PIMCOMP-NN
|
||||
checkout https://github.com/HEAPLab/pimsim-nn.git "$PIMSIM_COMMIT" backend-simulators/pim/pimsim-nn
|
||||
checkout https://github.com/protocolbuffers/protobuf.git "$PROTOBUF_COMMIT" /opt/protobuf
|
||||
|
||||
common=(-G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON
|
||||
-DCMAKE_EXE_LINKER_FLAGS=-fuse-ld=mold
|
||||
-DCMAKE_SHARED_LINKER_FLAGS=-fuse-ld=mold
|
||||
-DCMAKE_MODULE_LINKER_FLAGS=-fuse-ld=mold)
|
||||
|
||||
cmake -S /opt/protobuf -B /opt/protobuf/build "${common[@]}" \
|
||||
-Dprotobuf_BUILD_TESTS=OFF -Dprotobuf_ABSL_PROVIDER=module \
|
||||
-DABSL_PROPAGATE_CXX_STD=ON -DCMAKE_CXX_STANDARD=17
|
||||
cmake --build /opt/protobuf/build
|
||||
cmake --install /opt/protobuf/build
|
||||
ldconfig
|
||||
|
||||
llvm=onnx-mlir/llvm-project
|
||||
cmake -S "$llvm/llvm" -B "$llvm/build_release" "${common[@]}" \
|
||||
'-DLLVM_ENABLE_PROJECTS=mlir;clang' -DLLVM_ENABLE_RUNTIMES=openmp \
|
||||
-DLLVM_TARGETS_TO_BUILD=host -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_ENABLE_RTTI=ON \
|
||||
-DENABLE_LIBOMPTARGET=OFF -DLLVM_ENABLE_LIBEDIT=OFF \
|
||||
-DLLVM_PARALLEL_LINK_JOBS="$CMAKE_BUILD_PARALLEL_LEVEL"
|
||||
cmake --build "$llvm/build_release"
|
||||
|
||||
cmake -S . -B build_release "${common[@]}" \
|
||||
-DONNX_MLIR_ACCELERATORS=PIM -DLLVM_ENABLE_ASSERTIONS=ON \
|
||||
-DONNX_MLIR_ENABLE_JAVA=OFF -DONNX_MLIR_BUILD_TESTS=OFF \
|
||||
-DMLIR_DIR="$PWD/$llvm/build_release/lib/cmake/mlir"
|
||||
cmake --build ./build_release
|
||||
|
||||
cmake -S third_party/PIMCOMP-NN -B third_party/PIMCOMP-NN/build "${common[@]}"
|
||||
cmake --build third_party/PIMCOMP-NN/build --target PIMCOMP-NN
|
||||
sim=backend-simulators/pim/pimsim-nn
|
||||
cmake -S "$sim" -B "$sim/build" "${common[@]}"
|
||||
cmake --build "$sim/build"
|
||||
ctest --test-dir "$sim/build" --output-on-failure
|
||||
|
||||
crate=backend-simulators/pim/pim-simulator
|
||||
cargo build --locked --release --no-default-features --manifest-path "$crate/Cargo.toml" \
|
||||
--package pim-simulator --bin pim-simulator --jobs "$CMAKE_BUILD_PARALLEL_LEVEL"
|
||||
# The experiment driver uses cargo run. All dependencies must be available offline.
|
||||
cargo fetch --locked --manifest-path "$crate/Cargo.toml"
|
||||
mkdir -p /opt/artifact/provenance
|
||||
cp /opt/artifact/pins.env /opt/artifact/source.sha256 /opt/artifact/models.sha256 /opt/artifact/provenance/
|
||||
for dir in onnx-mlir "$llvm" third_party/PIMCOMP-NN "$sim" /opt/protobuf; do
|
||||
printf '%s %s\n' "$dir" "$(git -C "$dir" rev-parse HEAD)"
|
||||
git -C "$dir" submodule status --recursive
|
||||
done > /opt/artifact/provenance/revisions.txt
|
||||
dpkg-query -W > /opt/artifact/provenance/system-packages.txt
|
||||
.venv/bin/python -m pip freeze > /opt/artifact/provenance/python-packages.txt
|
||||
{ clang-19 --version; mold --version; cmake --version; rustc --version; } \
|
||||
> /opt/artifact/provenance/toolchain.txt
|
||||
# Runtime uses an arbitrary host UID. Cargo and the runners need writable caches
|
||||
# and ONNX-MLIR writes temporary shims/configurations inside its source tree.
|
||||
chmod -R a+rwX /opt/raptor /opt/cargo /opt/rustup
|
||||
@@ -1,5 +0,0 @@
|
||||
788088b908e233d924c7c26b997e89ee861290c7bc56783a306e8201d79aac8f validation/networks/pimcomp_models/resnet18/resnet18-v1-7.onnx
|
||||
c3231061d081bdd47884137b02134f85142752a39e87263c529cd14ed242b096 validation/networks/pimcomp_models/resnet34/resnet34-v1-7.onnx
|
||||
c960c195953423388733cd0e60712cf425ca1f8917e264f5cf98e028752c61cf validation/networks/pimcomp_models/googlenet/googlenet-12-no-lrn.onnx
|
||||
396cdea21e5e7d02c3f26f14d22ef20975171702493f5c5e79b8e0d896e541ef validation/networks/pimcomp_models/vgg8/vgg8-mnist-reconstructed.onnx
|
||||
5e7bd85dc60b252674f8d7e1ad24f2317d00dfb8c524826536698462de04620d validation/networks/pimcomp_models/yolo11n/yolo11n.onnx
|
||||
@@ -1,8 +0,0 @@
|
||||
# Raptor main at artifact preparation time. Do not replace this with a branch.
|
||||
RAPTOR_COMMIT=4a1fe710b2f0e4e9c0504f4fd9b4c4dd3df53b7d
|
||||
ONNX_MLIR_COMMIT=eb54c2afc46d00c6b196d1f275b6bfee17e12f69
|
||||
LLVM_COMMIT=0c2701fe7fa002e1befc5f86c268a7964f96d286
|
||||
PIMCOMP_COMMIT=7b6be6da4d33bf19f68d073eccac2a78e326a5af
|
||||
PIMSIM_COMMIT=17e37c15da5473362e53268dabdd07dff5fe8fbf
|
||||
PROTOBUF_COMMIT=6a6cd88c262ffdb1738167a47d5fcc7a3eb4edac
|
||||
RUST_VERSION=1.90.0
|
||||
@@ -1,59 +0,0 @@
|
||||
"""Plot planning and synchronization gains without hiding invalid programs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--input', type=Path, required=True)
|
||||
parser.add_argument('--output-dir', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
with args.input.open(newline='') as stream:
|
||||
rows = list(csv.DictReader(stream))
|
||||
if not rows:
|
||||
raise ValueError('The ablation CSV is empty')
|
||||
panels = [('plan', 'latency', 'latency_gain_percent', 'Planning: latency reduction (%)'),
|
||||
('plan', 'throughput', 'throughput_gain_percent', 'Planning: throughput increase (%)'),
|
||||
('sync', 'throughput', 'throughput_gain_percent', 'Synchronization: throughput increase (%)')]
|
||||
fig, axes = plt.subplots(3, 1, figsize=(11, 9), layout='constrained')
|
||||
for ax, (comparison, mode, field, label) in zip(axes, panels):
|
||||
selected = sorted((r for r in rows if r['comparison'] == comparison and r['mode'] == mode),
|
||||
key=lambda r: (r['arch'], r['model'], int(r['raptor_pipeline'])))
|
||||
for x, row in enumerate(selected):
|
||||
try:
|
||||
value = float(row[field].rstrip('%'))
|
||||
except (ValueError, TypeError):
|
||||
value = math.nan
|
||||
valid = row['functional_validation'] == row['baseline_functional_validation'] == 'PASS'
|
||||
if math.isfinite(value):
|
||||
ax.bar(x, value, color='#B3D5CA' if valid else '#FF9494',
|
||||
edgecolor='#222222', hatch='' if valid else '//')
|
||||
ax.annotate(f'{value:.1f}' + ('' if valid else ' INVALID'),
|
||||
(x, value), xytext=(0, 4 if value >= 0 else -4),
|
||||
textcoords='offset points', ha='center',
|
||||
va='bottom' if value >= 0 else 'top', fontsize=7)
|
||||
else:
|
||||
ax.text(x, 0, 'NA', ha='center', va='bottom', fontsize=8)
|
||||
ax.set_xticks(range(len(selected)),
|
||||
[f"{r['model']}\n{r['arch']} p{r['raptor_pipeline']}" for r in selected], fontsize=8)
|
||||
ax.set_ylabel(label)
|
||||
ax.axhline(0, color='#222222', linewidth=.7)
|
||||
ax.set_xlim(-.6, max(.6, len(selected) - .4))
|
||||
ax.margins(y=.3)
|
||||
fig.suptitle('Raptor ablation (red hatching: functional validation failed)')
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
for extension in ('pdf', 'svg', 'png'):
|
||||
fig.savefig(args.output_dir / f'ablation.{extension}', dpi=200)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,39 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
|
||||
source pins.env
|
||||
repo=$(git -C .. rev-parse --show-toplevel)
|
||||
test "$(git -C "$repo" rev-parse "$RAPTOR_COMMIT^{commit}")" = "$RAPTOR_COMMIT"
|
||||
for item in "onnx-mlir:$ONNX_MLIR_COMMIT" \
|
||||
"third_party/PIMCOMP-NN:$PIMCOMP_COMMIT" \
|
||||
"backend-simulators/pim/pimsim-nn:$PIMSIM_COMMIT"; do
|
||||
path=${item%:*}
|
||||
expected=${item##*:}
|
||||
actual=$(git -C "$repo" rev-parse "$RAPTOR_COMMIT:$path")
|
||||
test "$actual" = "$expected"
|
||||
done
|
||||
if [[ "${1:-}" != --overlay-only ]]; then
|
||||
# Include the complete compiler and evaluation code, plus only the suite models.
|
||||
# The last two paths are the targets of the suite's relative model symlinks.
|
||||
git -C "$repo" archive --format=tar "$RAPTOR_COMMIT" \
|
||||
CMakeLists.txt README.md .gitmodules src test docs backend-simulators \
|
||||
validation/README.md validation/validate.py validation/raptor_validation \
|
||||
validation/tools validation/pimsim_configs validation/networks/pimcomp_models \
|
||||
validation/networks/resnet18/depth_68/resnet18_depth_68.onnx \
|
||||
validation/networks/yolo11n/depth_51/yolo11n_depth_51.onnx \
|
||||
| gzip -n > source.tar.gz.tmp
|
||||
mv source.tar.gz.tmp source.tar.gz
|
||||
sha256sum source.tar.gz > source.sha256
|
||||
fi
|
||||
overlay=(validation/raptor_validation/experiment_scheduler.py
|
||||
validation/tools/pim/pimcomp/compare/run_pimcomp_models.py
|
||||
validation/tools/pim/pimcomp/compare/compare_raptor_pimcomp_model.py
|
||||
validation/tools/pim/ablation/run_ablation.py
|
||||
validation/tools/pim/pimcomp/compare/README.md
|
||||
validation/tools/pim/ablation/README.md)
|
||||
for path in "${overlay[@]}"; do
|
||||
mkdir -p "validation-overlay/$(dirname "$path")"
|
||||
cp "$repo/$path" "validation-overlay/$path"
|
||||
done
|
||||
sha256sum "${overlay[@]/#/validation-overlay/}" > validation-overlay.sha256
|
||||
printf 'Prepared Raptor %s\n' "$RAPTOR_COMMIT"
|
||||
@@ -1,23 +0,0 @@
|
||||
# Evaluation and ONNX-MLIR build dependencies. The Graph Explorer is not required.
|
||||
cmake==3.31.6
|
||||
colorama==0.4.6
|
||||
contourpy==1.3.2
|
||||
cycler==0.12.1
|
||||
execnet==2.1.1
|
||||
fonttools==4.58.0
|
||||
iniconfig==2.1.0
|
||||
kiwisolver==1.4.8
|
||||
lit==15.0.7
|
||||
matplotlib==3.10.3
|
||||
numpy==2.2.6
|
||||
onnx==1.17.0
|
||||
packaging==25.0
|
||||
pillow==11.2.1
|
||||
pluggy==1.5.0
|
||||
protobuf==7.34.0
|
||||
pyparsing==3.2.3
|
||||
pytest==8.3.5
|
||||
pytest-xdist==3.6.1
|
||||
python-dateutil==2.9.0.post0
|
||||
PyYAML==6.0.2
|
||||
six==1.17.0
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
"""Container commands for the pinned Raptor paper artifact."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
from html import escape
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REPO = Path('/opt/raptor')
|
||||
PYTHON = REPO / '.venv/bin/python'
|
||||
COMPARE = Path('validation/tools/pim/pimcomp/compare')
|
||||
ABLATION = Path('validation/tools/pim/ablation/run_ablation.py')
|
||||
|
||||
|
||||
def stage(name: str, command: list[str], root: Path) -> dict:
|
||||
print(f'[{name}] {command}', flush=True)
|
||||
start = time.monotonic()
|
||||
with (root / f'{name}.log').open('wb') as log:
|
||||
with subprocess.Popen(command, cwd=REPO, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT) as process:
|
||||
for line in process.stdout:
|
||||
sys.stdout.buffer.write(line)
|
||||
sys.stdout.buffer.flush()
|
||||
log.write(line)
|
||||
returncode = process.wait()
|
||||
return {'command': command, 'exit_code': returncode,
|
||||
'seconds': round(time.monotonic() - start, 3)}
|
||||
|
||||
|
||||
def plots(root: Path, smoke: bool) -> dict:
|
||||
commands = {'ablation-plots': [str(PYTHON), str(HERE / 'plot_ablation.py'),
|
||||
'--input', str(root / 'ablation/results_ablation.csv'),
|
||||
'--output-dir', str(root / 'plots/ablation')]}
|
||||
if not smoke:
|
||||
commands['comparison-plots'] = [str(PYTHON), str(COMPARE / 'generate_plots.py'),
|
||||
'--input', str(root / 'comparison/results_comparison.csv'),
|
||||
'--output-dir', str(root / 'plots/comparison')]
|
||||
return {name: stage(name, command, root) for name, command in commands.items()}
|
||||
|
||||
|
||||
def show_results(root: Path) -> None:
|
||||
page = ['<!doctype html><html lang="en"><meta charset="utf-8">',
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
||||
'<title>Raptor results</title><style>',
|
||||
'body{font:16px sans-serif;max-width:1100px;margin:2rem auto;padding:0 1rem}',
|
||||
'img{max-width:100%}table{border-collapse:collapse;font-size:13px}',
|
||||
'th,td{padding:6px;border:1px solid #ccc;white-space:nowrap}',
|
||||
'.table{overflow-x:auto}</style><h1>Raptor results</h1>',
|
||||
'<p>Functional validation status is shown in the tables and plots.</p>']
|
||||
for title, relative in (
|
||||
('Comparison', 'plots/comparison/png/performance_energy_compact.png'),
|
||||
('Pipeline throughput', 'plots/comparison/png/raptor_pipeline_throughput.png'),
|
||||
('Ablation', 'plots/ablation/ablation.png'),
|
||||
):
|
||||
if (root / relative).is_file():
|
||||
page.append(f'<h2>{title}</h2><a href="{relative}"><img src="{relative}" alt="{title}"></a>')
|
||||
for title, relative in (('Comparison', 'comparison/results_comparison.csv'),
|
||||
('Ablation', 'ablation/results_ablation.csv')):
|
||||
path = root / relative
|
||||
if path.is_file():
|
||||
page.append(f'<h2>{title} data</h2><p><a href="{relative}">Download CSV</a></p><div class="table"><table>')
|
||||
with path.open(newline='') as stream:
|
||||
for index, row in enumerate(csv.reader(stream)):
|
||||
tag = 'th' if index == 0 else 'td'
|
||||
page.append('<tr>' + ''.join(f'<{tag}>{escape(value)}</{tag}>' for value in row) + '</tr>')
|
||||
page.append('</table></div>')
|
||||
page.append('<h2>Files</h2><ul>')
|
||||
for path in sorted([*root.glob('*.log'), *root.glob('plots/*')]):
|
||||
relative = path.relative_to(root).as_posix()
|
||||
page.append(f'<li><a href="{relative}">{escape(relative)}</a></li>')
|
||||
page.append('</ul></html>')
|
||||
(root / 'index.html').write_text('\n'.join(page) + '\n')
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command', choices=('reproduce', 'smoke', 'plots'))
|
||||
parser.add_argument('--smoke', action='store_true', help='Plot the smoke results.')
|
||||
parser.add_argument('--jobs', type=int, default=int(os.environ.get('JOBS', len(os.sched_getaffinity(0)))))
|
||||
parser.add_argument('--threads-per-job', type=int,
|
||||
default=int(os.environ.get('THREADS_PER_JOB', len(os.sched_getaffinity(0)))))
|
||||
args = parser.parse_args()
|
||||
smoke = args.command == 'smoke' or args.smoke
|
||||
root = Path('/results') / ('smoke' if smoke else 'full')
|
||||
os.environ['CARGO_NET_OFFLINE'] = 'true'
|
||||
if args.command == 'plots':
|
||||
manifest_path = root / 'run.json'
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
records = plots(root, smoke)
|
||||
manifest['stages'].update(records)
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
show_results(root)
|
||||
return int(any(record['exit_code'] for record in records.values()))
|
||||
if root.exists():
|
||||
parser.error(f'{root} exists. Select a fresh OUTPUT_DIR to prevent stale result reuse.')
|
||||
jobs = args.jobs
|
||||
if jobs < 1 or args.threads_per_job < 1:
|
||||
parser.error('jobs and threads-per-job must be positive')
|
||||
root.mkdir(parents=True)
|
||||
shutil.copytree(HERE / 'provenance', root / 'provenance')
|
||||
# Copy the artifact scripts so each result identifies its orchestration code.
|
||||
shutil.copytree(HERE, root / 'provenance/artifact',
|
||||
ignore=shutil.ignore_patterns('provenance', '__pycache__'))
|
||||
manifest = {'started_utc': datetime.now(timezone.utc).isoformat(),
|
||||
'profile': 'smoke' if smoke else 'full', 'image_id': os.environ.get('ARTIFACT_IMAGE_ID'),
|
||||
'platform': platform.platform(), 'machine': platform.machine(),
|
||||
'cpu_count': os.cpu_count(), 'jobs': jobs, 'threads_per_job': args.threads_per_job,
|
||||
'batch_size': 64, 'fast': False, 'stages': {}}
|
||||
common = ['--jobs', str(jobs), '--threads-per-job', str(args.threads_per_job),
|
||||
'--batch-size', '64', '--no-fast']
|
||||
subset = ['--models', 'vgg8', '--archs', 'arch-a', '--mode', 'latency', '--pipeline', '1'] if smoke else []
|
||||
commands = {
|
||||
'experiments': [str(PYTHON), str(COMPARE / 'run_pimcomp_models.py'),
|
||||
'--out-dir', str(root / 'comparison'),
|
||||
'--with-ablation', '--ablation-out-dir', str(root / 'ablation'),
|
||||
'--common-dir', str(root / 'references'), *common, *subset],
|
||||
}
|
||||
manifest_path = root / 'run.json'
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
for name, command in commands.items():
|
||||
manifest['stages'][name] = stage(name, command, root)
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
manifest['stages'].update(plots(root, smoke))
|
||||
manifest['finished_utc'] = datetime.now(timezone.utc).isoformat()
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
show_results(root)
|
||||
return int(any(record['exit_code'] for record in manifest['stages'].values()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -4,18 +4,17 @@ use mimalloc::MiMalloc;
|
||||
static GLOBAL: MiMalloc = MiMalloc;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, ValueEnum};
|
||||
use clap::Parser;
|
||||
use glob::glob;
|
||||
use pimcore::binary_to_instruction::binary_to_executor;
|
||||
use pimcore::cpu::crossbar::Crossbar;
|
||||
use pimcore::json_to_instruction::json_to_executor;
|
||||
use pimcore::memory_manager::CoreMemory;
|
||||
use pimcore::tracing::TRACER;
|
||||
use pimcore::{DiagnosticSchedulePolicy, DiagnosticScheduleTarget};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, File};
|
||||
use std::io::BufReader;
|
||||
use std::io::{BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Program to simulate core execution configuration
|
||||
@@ -45,79 +44,14 @@ struct Args {
|
||||
/// Comma separated list of (address,size) for memory output dump
|
||||
#[arg(short, long, value_delimiter = ',', num_args = 1.., value_name = "ADDR,SIZE")]
|
||||
dump: Vec<usize>,
|
||||
|
||||
/// Simulator execution mode
|
||||
#[arg(long, value_enum, default_value_t = ExecutionMode::Latency)]
|
||||
mode: ExecutionMode,
|
||||
|
||||
/// Number of inputs to execute (required in throughput mode)
|
||||
#[arg(long)]
|
||||
batch_size: Option<u32>,
|
||||
|
||||
/// Directory containing input_*.bin files, one per batch entry
|
||||
#[arg(long = "input-dir")]
|
||||
input_dir: PathBuf,
|
||||
|
||||
/// Optional directory for per-iteration output dumps
|
||||
#[arg(long)]
|
||||
batch_output_dir: Option<PathBuf>,
|
||||
|
||||
/// Optional JSONL shadow provenance trace
|
||||
#[arg(long)]
|
||||
provenance_trace: Option<PathBuf>,
|
||||
|
||||
/// Diagnostic-only barrier between global throughput iterations
|
||||
#[arg(long)]
|
||||
provenance_global_barrier: bool,
|
||||
|
||||
/// Diagnostic-only ready-core delay, formatted as CORE:CYCLES
|
||||
#[arg(long, value_name = "CORE:CYCLES")]
|
||||
provenance_core_stall: Option<String>,
|
||||
|
||||
/// Diagnostic scheduler policy; greedy is the unchanged default
|
||||
#[arg(long, value_enum, default_value_t = DiagnosticSchedulePolicyArg::Greedy)]
|
||||
diagnostic_schedule_policy: DiagnosticSchedulePolicyArg,
|
||||
|
||||
/// Deterministic seed for the randomized diagnostic scheduler
|
||||
#[arg(long, default_value_t = 0)]
|
||||
diagnostic_schedule_seed: u64,
|
||||
|
||||
/// Adversarial target: WCORE:WPC:RCORE:RPC:BEGIN:END[:READER_ITER:WRITER_MIN_ITER]
|
||||
#[arg(long, value_name = "WCORE:WPC:RCORE:RPC:BEGIN:END[:RITER:WMIN]")]
|
||||
diagnostic_schedule_target: Option<String>,
|
||||
|
||||
/// Maximum number of target-consumer deferrals
|
||||
#[arg(long, default_value_t = 10_000)]
|
||||
diagnostic_schedule_deferral_budget: u64,
|
||||
|
||||
/// Diagnostic delay applied when a target reader reaches its PC, formatted as CORE:PC:CYCLES or CORE:PC:ITERATION:CYCLES
|
||||
#[arg(long, value_name = "CORE:PC[:ITERATION]:CYCLES")]
|
||||
diagnostic_target_stall: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, ValueEnum)]
|
||||
enum ExecutionMode {
|
||||
Latency,
|
||||
Throughput,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
enum DiagnosticSchedulePolicyArg {
|
||||
Greedy,
|
||||
Randomized,
|
||||
Adversarial,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let config_json = retrieve_config(&args)?;
|
||||
let batch_size = batch_size(&args)?;
|
||||
let input_regions = input_regions(&config_json)?;
|
||||
let input_data = retrieve_inputs(&args, batch_size)?;
|
||||
let inputs: Vec<&[u8]> = input_data.iter().map(Vec::as_slice).collect();
|
||||
let mut core_inputs = retrieve_cores(&args)?;
|
||||
let memory = retrieve_memory(&args)?;
|
||||
let config_json = retrive_config(&args)?;
|
||||
let mut core_inputs = retrive_cores(&args)?;
|
||||
let memory = retrive_memory(&args)?;
|
||||
let global_crossbars = get_crossbars(&config_json, &args).unwrap();
|
||||
let crossbars = map_crossbars_to_cores(&config_json, &args, &global_crossbars);
|
||||
let mut executor = match &mut core_inputs {
|
||||
@@ -129,161 +63,15 @@ fn main() -> Result<()> {
|
||||
}
|
||||
};
|
||||
set_memory(&mut executor, memory);
|
||||
if let Some(path) = &args.provenance_trace {
|
||||
executor.enable_provenance(path)?;
|
||||
}
|
||||
executor.set_provenance_global_barrier(args.provenance_global_barrier);
|
||||
if let Some(spec) = args.provenance_core_stall.as_deref() {
|
||||
let (core, cycles) = parse_core_stall(spec)?;
|
||||
executor.set_provenance_core_stall(core, cycles);
|
||||
}
|
||||
executor.set_diagnostic_schedule_policy(match args.diagnostic_schedule_policy {
|
||||
DiagnosticSchedulePolicyArg::Greedy => DiagnosticSchedulePolicy::Greedy,
|
||||
DiagnosticSchedulePolicyArg::Randomized => DiagnosticSchedulePolicy::Randomized,
|
||||
DiagnosticSchedulePolicyArg::Adversarial => DiagnosticSchedulePolicy::Adversarial,
|
||||
});
|
||||
executor.set_diagnostic_schedule_seed(args.diagnostic_schedule_seed);
|
||||
executor.set_diagnostic_schedule_deferral_budget(args.diagnostic_schedule_deferral_budget);
|
||||
if let Some(spec) = args.diagnostic_target_stall.as_deref() {
|
||||
let (core, pc, iteration, cycles) = parse_target_stall(spec)?;
|
||||
executor.set_diagnostic_target_stall(core, pc, iteration, cycles);
|
||||
}
|
||||
if let Some(spec) = args.diagnostic_schedule_target.as_deref() {
|
||||
executor.set_diagnostic_schedule_target(parse_schedule_target(spec)?);
|
||||
} else if matches!(
|
||||
args.diagnostic_schedule_policy,
|
||||
DiagnosticSchedulePolicyArg::Adversarial
|
||||
) {
|
||||
bail!("adversarial scheduling requires --diagnostic-schedule-target");
|
||||
}
|
||||
TRACER
|
||||
.lock()
|
||||
.unwrap()
|
||||
.init(executor.cpu().num_core(), args.output.clone());
|
||||
let dumps = dump_ranges(&args.dump)?;
|
||||
let batch_outputs = executor.execute_batch(&inputs, &input_regions, &dumps)?;
|
||||
fs::write(
|
||||
&args.output,
|
||||
batch_outputs
|
||||
.last()
|
||||
.context("simulation produced no output")?,
|
||||
)?;
|
||||
if let Some(batch_output_dir) = args.batch_output_dir {
|
||||
write_batch_outputs(batch_output_dir, batch_outputs)?;
|
||||
}
|
||||
executor.execute()?;
|
||||
dump_memory(executor, &args)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_core_stall(spec: &str) -> Result<(usize, u64)> {
|
||||
let (core, cycles) = spec
|
||||
.split_once(':')
|
||||
.context("--provenance-core-stall must be CORE:CYCLES")?;
|
||||
let core = core.parse().context("invalid stalled core")?;
|
||||
let cycles = cycles.parse().context("invalid stall cycle count")?;
|
||||
if cycles == 0 {
|
||||
bail!("--provenance-core-stall cycles must be positive");
|
||||
}
|
||||
Ok((core, cycles))
|
||||
}
|
||||
|
||||
fn parse_schedule_target(spec: &str) -> Result<DiagnosticScheduleTarget> {
|
||||
let values: Vec<usize> = spec
|
||||
.split(':')
|
||||
.map(|value| {
|
||||
value
|
||||
.parse()
|
||||
.with_context(|| format!("invalid schedule target field: {value}"))
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if values.len() != 6 && values.len() != 8 {
|
||||
bail!(
|
||||
"--diagnostic-schedule-target requires WCORE:WPC:RCORE:RPC:BEGIN:END with optional RITER:WMIN"
|
||||
);
|
||||
}
|
||||
if values[5] <= values[4] {
|
||||
bail!("schedule target address end must be greater than begin");
|
||||
}
|
||||
Ok(DiagnosticScheduleTarget {
|
||||
writer_core: values[0],
|
||||
writer_pc: values[1],
|
||||
reader_core: values[2],
|
||||
reader_pc: values[3],
|
||||
address_begin: values[4],
|
||||
address_end: values[5],
|
||||
reader_iteration: (values.len() == 8).then_some(values[6] as u32),
|
||||
writer_min_iteration: (values.len() == 8).then_some(values[7] as u32),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_target_stall(spec: &str) -> Result<(usize, usize, Option<u32>, u64)> {
|
||||
let values: Vec<&str> = spec.split(':').collect();
|
||||
if values.len() != 3 && values.len() != 4 {
|
||||
bail!("--diagnostic-target-stall must be CORE:PC:CYCLES or CORE:PC:ITERATION:CYCLES");
|
||||
}
|
||||
let core = values[0].parse().context("invalid target-stall core")?;
|
||||
let pc = values[1].parse().context("invalid target-stall PC")?;
|
||||
let (iteration, cycle_field) = if values.len() == 4 {
|
||||
(
|
||||
Some(
|
||||
values[2]
|
||||
.parse()
|
||||
.context("invalid target-stall iteration")?,
|
||||
),
|
||||
values[3],
|
||||
)
|
||||
} else {
|
||||
(None, values[2])
|
||||
};
|
||||
let cycles = cycle_field
|
||||
.parse()
|
||||
.context("invalid target-stall cycle count")?;
|
||||
if cycles == 0 {
|
||||
bail!("--diagnostic-target-stall cycles must be positive");
|
||||
}
|
||||
Ok((core, pc, iteration, cycles))
|
||||
}
|
||||
|
||||
fn batch_size(args: &Args) -> Result<u32> {
|
||||
match (&args.mode, args.batch_size) {
|
||||
(ExecutionMode::Latency, None | Some(1)) => Ok(1),
|
||||
(ExecutionMode::Latency, Some(_)) => bail!("latency mode requires batch size 1"),
|
||||
(ExecutionMode::Throughput, Some(0)) => bail!("batch size must be positive"),
|
||||
(ExecutionMode::Throughput, Some(batch_size)) => Ok(batch_size),
|
||||
(ExecutionMode::Throughput, None) => bail!("throughput mode requires --batch-size"),
|
||||
}
|
||||
}
|
||||
|
||||
fn input_regions(config: &Value) -> Result<Vec<(usize, usize)>> {
|
||||
let addresses = config
|
||||
.get("inputs_addresses")
|
||||
.and_then(Value::as_array)
|
||||
.context("config.json has no inputs_addresses array")?;
|
||||
let sizes = config
|
||||
.get("inputs_sizes")
|
||||
.and_then(Value::as_array)
|
||||
.context("config.json has no inputs_sizes array")?;
|
||||
if addresses.len() != sizes.len() {
|
||||
bail!("config.json input address/size count mismatch");
|
||||
}
|
||||
addresses
|
||||
.iter()
|
||||
.zip(sizes)
|
||||
.map(|(address, size)| {
|
||||
Ok((
|
||||
usize::try_from(address.as_u64().context("invalid input address")?)?,
|
||||
usize::try_from(size.as_u64().context("invalid input size")?)?,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn retrieve_inputs(args: &Args, batch_size: u32) -> Result<Vec<Vec<u8>>> {
|
||||
(0..batch_size)
|
||||
.map(|index| args.input_dir.join(format!("input_{index}.bin")))
|
||||
.map(|path| fs::read(&path).with_context(|| format!("Failed to read input file: {path:?}")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn map_crossbars_to_cores<'c>(
|
||||
config: &Value,
|
||||
args: &Args,
|
||||
@@ -326,7 +114,7 @@ fn map_crossbars_to_cores<'c>(
|
||||
let path_as_str = real_path.to_str().unwrap();
|
||||
assert!(
|
||||
global_crossbars.contains_key(path_as_str),
|
||||
"symlink points to {:?}\n a crossbar that was not stored",
|
||||
"symlink point to {:?}\n a not stored crossbar",
|
||||
real_path
|
||||
);
|
||||
|
||||
@@ -343,7 +131,7 @@ fn map_crossbars_to_cores<'c>(
|
||||
fn get_crossbars(config: &Value, args: &Args) -> anyhow::Result<HashMap<String, Crossbar>> {
|
||||
let xbar_size = config.get("xbar_size").unwrap().as_array().unwrap();
|
||||
let rows_crossbar = xbar_size[0].as_i64().unwrap() as usize;
|
||||
let column_crossbar = xbar_size[1].as_i64().unwrap() as usize;
|
||||
let column_corssbar = xbar_size[1].as_i64().unwrap() as usize;
|
||||
let mut res = HashMap::new();
|
||||
|
||||
if let Some(folder) = args.folder.as_ref() {
|
||||
@@ -366,7 +154,7 @@ fn get_crossbars(config: &Value, args: &Args) -> anyhow::Result<HashMap<String,
|
||||
let bytes = std::fs::read(weight_file.path()).expect("Failed to read binary file");
|
||||
let stored_row_bytes = bytes.len() / rows_crossbar;
|
||||
let mut crossbar = Crossbar::new(
|
||||
std::cmp::max(column_crossbar * 4, stored_row_bytes),
|
||||
std::cmp::max(column_corssbar * 4, stored_row_bytes),
|
||||
rows_crossbar,
|
||||
CoreMemory::new(),
|
||||
);
|
||||
@@ -386,22 +174,21 @@ fn get_crossbars(config: &Value, args: &Args) -> anyhow::Result<HashMap<String,
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn dump_ranges(values: &[usize]) -> Result<Vec<(usize, usize)>> {
|
||||
if !values.len().is_multiple_of(2) {
|
||||
bail!("memory dump requires address,size pairs");
|
||||
}
|
||||
Ok(values
|
||||
fn dump_memory(mut executor: pimcore::Executable, args: &Args) -> Result<()> {
|
||||
let dumps: Vec<(usize, usize)> = args
|
||||
.dump
|
||||
.chunks_exact(2)
|
||||
.map(|chunk| (chunk[0], chunk[1]))
|
||||
.collect())
|
||||
}
|
||||
.collect();
|
||||
let mut out_file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(&args.output)
|
||||
.with_context(|| format!("cannot open file {:?} for writing", args.output))?;
|
||||
|
||||
fn write_batch_outputs(output_dir: PathBuf, outputs: Vec<Vec<u8>>) -> Result<()> {
|
||||
fs::create_dir_all(&output_dir)
|
||||
.with_context(|| format!("cannot create batch output directory {output_dir:?}"))?;
|
||||
for (iteration, output) in outputs.into_iter().enumerate() {
|
||||
let path = output_dir.join(format!("output_{iteration:06}.bin"));
|
||||
fs::write(&path, output).with_context(|| format!("cannot write batch output {path:?}"))?;
|
||||
for (address, size) in dumps {
|
||||
out_file.write_all(executor.cpu_mut().host().load::<u8>(address, size).unwrap()[0])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -410,7 +197,7 @@ fn set_memory(executor: &mut pimcore::Executable, memory: Vec<u8>) {
|
||||
executor.cpu_mut().host().execute_store(0, &memory).unwrap();
|
||||
}
|
||||
|
||||
fn retrieve_memory(args: &Args) -> Result<Vec<u8>> {
|
||||
fn retrive_memory(args: &Args) -> Result<Vec<u8>> {
|
||||
let memory_path = if let Some(mem_override) = &args.memory {
|
||||
mem_override.clone()
|
||||
} else if let Some(folder) = &args.folder.as_ref() {
|
||||
@@ -450,7 +237,7 @@ enum CoreInputs {
|
||||
Binary(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
fn retrieve_cores(args: &Args) -> Result<CoreInputs, anyhow::Error> {
|
||||
fn retrive_cores(args: &Args) -> Result<CoreInputs, anyhow::Error> {
|
||||
if let Some(cores_override) = &args.cores {
|
||||
let first_extension = cores_override
|
||||
.first()
|
||||
@@ -523,7 +310,7 @@ fn core_sort_key(path: &PathBuf) -> i32 {
|
||||
stem.parse::<i32>().unwrap()
|
||||
}
|
||||
|
||||
fn retrieve_config(args: &Args) -> Result<Value, anyhow::Error> {
|
||||
fn retrive_config(args: &Args) -> Result<Value, anyhow::Error> {
|
||||
let config_path: PathBuf = {
|
||||
let override_path = args.config.as_ref();
|
||||
let folder = args.folder.as_ref();
|
||||
|
||||
@@ -80,19 +80,19 @@ fn read_i32_le(bytes: &[u8], offset: usize) -> i32 {
|
||||
|
||||
fn parse_binary_records(bytes: &[u8]) -> Result<Vec<InstructionRecord>> {
|
||||
ensure!(bytes.len() >= HEADER_SIZE, "binary core file too small");
|
||||
ensure!(&bytes[0..4] == MAGIC, "invalid Pim binary magic");
|
||||
ensure!(&bytes[0..4] == MAGIC, "invalid PIM binary magic");
|
||||
|
||||
let version = read_u32_le(bytes, 4);
|
||||
ensure!(
|
||||
version == VERSION,
|
||||
"unsupported Pim binary version {version}"
|
||||
"unsupported PIM binary version {version}"
|
||||
);
|
||||
|
||||
let instruction_count = read_u32_le(bytes, 8) as usize;
|
||||
let expected_len = HEADER_SIZE + instruction_count * RECORD_SIZE;
|
||||
ensure!(
|
||||
bytes.len() == expected_len,
|
||||
"Pim binary size mismatch: expected {expected_len} bytes, got {}",
|
||||
"PIM binary size mismatch: expected {expected_len} bytes, got {}",
|
||||
bytes.len()
|
||||
);
|
||||
|
||||
@@ -326,16 +326,12 @@ fn append_record(
|
||||
inst_builder.make_inst(recv, inst_data_builder.build());
|
||||
}
|
||||
31 => {
|
||||
inst_data_builder.set_offset_select_value(generic1, generic2);
|
||||
inst_builder.make_inst(wait, inst_data_builder.build());
|
||||
}
|
||||
32 => {
|
||||
inst_data_builder
|
||||
.set_imm_core(r2_or_imm + 1)
|
||||
.set_offset_select_value(generic1, 0);
|
||||
inst_builder.make_inst(sync, inst_data_builder.build());
|
||||
}
|
||||
_ => bail!("unsupported Pim binary opcode {opcode}"),
|
||||
_ => bail!("unsupported PIM binary opcode {opcode}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2,48 +2,17 @@ use crate::utility::AddressArg;
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use std::{collections::HashMap, fmt::Debug};
|
||||
|
||||
use super::{DiagnosticSchedulePolicy, DiagnosticScheduleTarget};
|
||||
use crate::{
|
||||
cpu::crossbar::Crossbar,
|
||||
instruction_set::Instructions,
|
||||
memory_manager::{CoreMemory, MemoryStorable, type_traits::TryToUsize},
|
||||
provenance::ProvenanceTracker,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub mod crossbar;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CPU<'a> {
|
||||
cores: Box<[Core<'a>]>,
|
||||
batch_outputs: Option<BatchOutputs>,
|
||||
provenance: Option<ProvenanceTracker>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct BatchOutputs {
|
||||
iteration: usize,
|
||||
ranges: Vec<(usize, usize)>,
|
||||
outputs: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl BatchOutputs {
|
||||
fn record(&mut self, address: usize, bytes: &[u8]) {
|
||||
let output = &mut self.outputs[self.iteration];
|
||||
let store_end = address + bytes.len();
|
||||
let mut output_offset = 0;
|
||||
for &(range_address, range_size) in &self.ranges {
|
||||
let start = address.max(range_address);
|
||||
let end = store_end.min(range_address + range_size);
|
||||
if start < end {
|
||||
let size = end - start;
|
||||
output[output_offset + start - range_address
|
||||
..output_offset + start - range_address + size]
|
||||
.copy_from_slice(&bytes[start - address..start - address + size]);
|
||||
}
|
||||
output_offset += range_size;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> CPU<'a> {
|
||||
@@ -56,320 +25,9 @@ impl<'a> CPU<'a> {
|
||||
}
|
||||
Self {
|
||||
cores: cores.into(),
|
||||
batch_outputs: None,
|
||||
provenance: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enable_provenance(
|
||||
&mut self,
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> std::io::Result<()> {
|
||||
self.provenance = Some(ProvenanceTracker::new(self.cores.len(), path)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn begin_provenance_batch(&mut self, batch_size: usize) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.begin_batch(batch_size);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_execution_context(
|
||||
&mut self,
|
||||
cycle: u64,
|
||||
core: usize,
|
||||
pc: usize,
|
||||
iteration: u32,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.set_context(cycle, core, pc, iteration);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_input_store(&mut self, address: usize, size: usize, sample: u32) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.input_store(address, size, sample);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_global_store_from_local(
|
||||
&mut self,
|
||||
core: usize,
|
||||
global_address: usize,
|
||||
local_address: usize,
|
||||
size: usize,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.global_store_from_local(core, global_address, local_address, size);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_global_load_to_local(
|
||||
&mut self,
|
||||
core: usize,
|
||||
global_address: usize,
|
||||
local_address: usize,
|
||||
size: usize,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.global_load_to_local(core, global_address, local_address, size);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_local_copy(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
size: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.local_copy(core, destination, source, size, operation);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_local_strided_copy(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
element_size: usize,
|
||||
stride: usize,
|
||||
element_count: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.local_strided_copy(
|
||||
core,
|
||||
destination,
|
||||
source,
|
||||
element_size,
|
||||
stride,
|
||||
element_count,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_local_transform(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
sources: &[(usize, usize)],
|
||||
output_size: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.local_transform(core, destination, sources, output_size, operation);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_local_broadcast_transform(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
source_size: usize,
|
||||
output_size: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.local_broadcast_transform(
|
||||
core,
|
||||
destination,
|
||||
source,
|
||||
source_size,
|
||||
output_size,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_local_mvm_transform(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
element_size: usize,
|
||||
output_size: usize,
|
||||
used_rows: &[bool],
|
||||
operation: &'static str,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.local_mvm_transform(
|
||||
core,
|
||||
destination,
|
||||
source,
|
||||
element_size,
|
||||
output_size,
|
||||
used_rows,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_send_transfer(
|
||||
&mut self,
|
||||
sender: usize,
|
||||
receiver: usize,
|
||||
source: usize,
|
||||
destination: usize,
|
||||
size: usize,
|
||||
) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.send_transfer(sender, receiver, source, destination, size);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_provenance(&mut self) {
|
||||
if let Some(provenance) = &mut self.provenance {
|
||||
provenance.flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_schedule_stall(&mut self, core: usize, remaining_cycles: u64) {
|
||||
if let Some(provenance) = &self.provenance {
|
||||
provenance.schedule_stall(core, remaining_cycles);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_schedule_target_stall(
|
||||
&mut self,
|
||||
core: usize,
|
||||
pc: usize,
|
||||
remaining_cycles: u64,
|
||||
) {
|
||||
if let Some(provenance) = &self.provenance {
|
||||
provenance.schedule_target_stall(core, pc, remaining_cycles);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_schedule_config(&mut self, config: super::DiagnosticScheduleConfig) {
|
||||
if let Some(provenance) = &self.provenance {
|
||||
provenance.schedule_config(
|
||||
match config.policy {
|
||||
DiagnosticSchedulePolicy::Greedy => "greedy",
|
||||
DiagnosticSchedulePolicy::Randomized => "randomized",
|
||||
DiagnosticSchedulePolicy::Adversarial => "adversarial",
|
||||
},
|
||||
config.seed,
|
||||
config.target.map(|target| {
|
||||
json!({
|
||||
"writer_core": target.writer_core,
|
||||
"writer_pc": target.writer_pc,
|
||||
"reader_core": target.reader_core,
|
||||
"reader_pc": target.reader_pc,
|
||||
"address_begin": target.address_begin,
|
||||
"address_end": target.address_end,
|
||||
"reader_iteration": target.reader_iteration,
|
||||
"writer_min_iteration": target.writer_min_iteration,
|
||||
})
|
||||
}),
|
||||
config.deferral_budget,
|
||||
config.fixed_stall,
|
||||
config.fixed_target_stall,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_scheduler_event(
|
||||
&mut self,
|
||||
event: &'static str,
|
||||
core: usize,
|
||||
pc: usize,
|
||||
iteration: u32,
|
||||
reason: &'static str,
|
||||
selected_core: Option<usize>,
|
||||
target: Option<DiagnosticScheduleTarget>,
|
||||
deferrals: u64,
|
||||
) {
|
||||
if let Some(provenance) = &self.provenance {
|
||||
let target = target.map(|target| {
|
||||
json!({
|
||||
"writer_core": target.writer_core,
|
||||
"writer_pc": target.writer_pc,
|
||||
"reader_core": target.reader_core,
|
||||
"reader_pc": target.reader_pc,
|
||||
"address_begin": target.address_begin,
|
||||
"address_end": target.address_end,
|
||||
"reader_iteration": target.reader_iteration,
|
||||
"writer_min_iteration": target.writer_min_iteration,
|
||||
})
|
||||
});
|
||||
provenance.scheduler_event(json!({
|
||||
"event": event,
|
||||
"cycle": self.provenance_cycle(),
|
||||
"core": core,
|
||||
"pc": pc,
|
||||
"core_iteration": iteration,
|
||||
"reason": reason,
|
||||
"selected_core": selected_core,
|
||||
"target": target,
|
||||
"deferrals": deferrals,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
fn provenance_cycle(&self) -> u64 {
|
||||
self.provenance.as_ref().map_or(0, ProvenanceTracker::cycle)
|
||||
}
|
||||
|
||||
pub(crate) fn set_current_iteration(&mut self, iteration: u32) {
|
||||
if let Some(batch_outputs) = &mut self.batch_outputs {
|
||||
batch_outputs.iteration = iteration as usize;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_host_store_recording(
|
||||
&mut self,
|
||||
batch_size: usize,
|
||||
dump_ranges: &[(usize, usize)],
|
||||
) -> Result<()> {
|
||||
let mut initial = Vec::new();
|
||||
for &(address, size) in dump_ranges {
|
||||
initial.extend_from_slice(self.host().load::<u8>(address, size)?[0]);
|
||||
}
|
||||
self.batch_outputs = Some(BatchOutputs {
|
||||
iteration: 0,
|
||||
ranges: dump_ranges.to_vec(),
|
||||
outputs: vec![initial; batch_size],
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn store_to_host(
|
||||
&mut self,
|
||||
core: impl TryToUsize,
|
||||
host_address: impl AddressArg,
|
||||
core_address: impl AddressArg,
|
||||
size: impl TryToUsize,
|
||||
) -> Result<()> {
|
||||
let core = core.try_into().expect("core can not be negative");
|
||||
let host_address = host_address.to_address_usize()?;
|
||||
let core_address = core_address.to_address_usize()?;
|
||||
let size = size.try_into().context("size can not be negative")?;
|
||||
let Self {
|
||||
cores,
|
||||
batch_outputs,
|
||||
..
|
||||
} = self;
|
||||
let (host, cores) = cores.split_at_mut(1);
|
||||
let bytes = cores[core - 1].load::<u8>(core_address, size)?[0];
|
||||
host[0].execute_store(host_address, bytes)?;
|
||||
if let Some(batch_outputs) = batch_outputs {
|
||||
batch_outputs.record(host_address, bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn finish_host_store_recording(&mut self) -> Vec<Vec<u8>> {
|
||||
self.batch_outputs
|
||||
.take()
|
||||
.map_or_else(Vec::new, |batch_outputs| batch_outputs.outputs)
|
||||
}
|
||||
|
||||
pub fn host<'b>(&'b mut self) -> &'b mut Core<'a>
|
||||
where
|
||||
'a: 'b,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
cpu::{CPU, crossbar},
|
||||
instruction_set::{
|
||||
Instruction, InstructionData, InstructionStatus, InstructionType, VectorBitWidth,
|
||||
Instruction, InstructionData, InstructionStatus, InstructionType, VectorBitWith,
|
||||
helper::add_all,
|
||||
},
|
||||
memory_manager::{
|
||||
@@ -200,20 +200,20 @@ pub fn isa_simd(functor: InstructionType) -> bool {
|
||||
|
||||
pub fn dispatch_simd(
|
||||
functor: InstructionType,
|
||||
vector_bit_width: VectorBitWidth,
|
||||
vector_bit_with: VectorBitWith,
|
||||
) -> Result<InstructionType> {
|
||||
let VectorBitWidth {
|
||||
vector_input_bitwidth,
|
||||
vector_output_bitwidth,
|
||||
} = vector_bit_width;
|
||||
let VectorBitWith {
|
||||
vector_input_bitwith,
|
||||
vector_output_bitwith,
|
||||
} = vector_bit_with;
|
||||
let res = SIMD
|
||||
.get(&(functor as usize))
|
||||
.context("Request a non present simd")?
|
||||
.get(&(vector_input_bitwidth, vector_output_bitwidth))
|
||||
.get(&(vector_input_bitwith, vector_output_bitwith))
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Function not found for the requested size input:{} output:{}",
|
||||
vector_input_bitwidth, vector_output_bitwidth
|
||||
vector_input_bitwith, vector_output_bitwith
|
||||
)
|
||||
})?;
|
||||
Ok(*res)
|
||||
@@ -285,10 +285,6 @@ where
|
||||
let load = loads[0];
|
||||
let vec: Cow<[M]> = load.up();
|
||||
let matrix = crossbar.load::<M>(crossbar_stored_bytes)?[0];
|
||||
let used_rows: Vec<bool> = matrix
|
||||
.chunks_exact(crossbar_elem_width)
|
||||
.map(|row| row.iter().any(|value| *value != M::from_f32(0.0)))
|
||||
.collect();
|
||||
|
||||
// --- FAER IMPLEMENTATION ---
|
||||
|
||||
@@ -327,16 +323,6 @@ where
|
||||
|
||||
let res_up: Cow<[T]> = res.as_slice().up();
|
||||
core.execute_store(rd_val, res_up.as_ref());
|
||||
let _ = core;
|
||||
cores.provenance_local_mvm_transform(
|
||||
core_indx as usize,
|
||||
rd_val as usize,
|
||||
r1_val as usize,
|
||||
size_of::<F>(),
|
||||
res_up.len() * size_of::<T>(),
|
||||
&used_rows,
|
||||
"mvmul",
|
||||
);
|
||||
|
||||
TRACER.lock().unwrap().post_mvm::<F, M, T>(cores, data);
|
||||
Ok(InstructionStatus::Completed)
|
||||
@@ -403,14 +389,6 @@ where
|
||||
);
|
||||
let res_up: Cow<[T]> = res.as_slice().up();
|
||||
core.execute_store(rd_val, res_up.as_ref());
|
||||
let _ = core;
|
||||
cores.provenance_local_transform(
|
||||
core_indx as usize,
|
||||
rd_val,
|
||||
&[(r1_val, byte_len), (r2_val, byte_len)],
|
||||
byte_len,
|
||||
"vvadd",
|
||||
);
|
||||
TRACER.lock().unwrap().post_vvadd::<F, T>(cores, data);
|
||||
Ok(InstructionStatus::Completed)
|
||||
}
|
||||
@@ -496,13 +474,6 @@ where
|
||||
);
|
||||
let res_up: Cow<[T]> = res.as_slice().up();
|
||||
core.execute_store(rd_val, res_up.as_ref());
|
||||
cores.provenance_local_transform(
|
||||
core_indx as usize,
|
||||
rd_val,
|
||||
&[(r1_val, byte_len), (r2_val, byte_len)],
|
||||
byte_len,
|
||||
"vvmul",
|
||||
);
|
||||
Ok(InstructionStatus::Completed)
|
||||
}
|
||||
|
||||
@@ -809,15 +780,6 @@ where
|
||||
);
|
||||
}
|
||||
core.execute_store(destination, &result)?;
|
||||
cores.provenance_local_strided_copy(
|
||||
core_indx as usize,
|
||||
destination as usize,
|
||||
source,
|
||||
size_of::<F>(),
|
||||
stride,
|
||||
element_count,
|
||||
"vmv",
|
||||
);
|
||||
Ok(InstructionStatus::Completed)
|
||||
}
|
||||
|
||||
@@ -837,23 +799,16 @@ pub fn vrsl(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus>
|
||||
#[inline(never)]
|
||||
pub fn ld(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus> {
|
||||
TRACER.lock().unwrap().pre_ld(cores, data);
|
||||
let (core_index, rd, r1, _, imm_len, offset_select, offset_value) =
|
||||
let (core, rd, r1, _, imm_len, offset_select, offset_value) =
|
||||
data.get_core_rd_r1_r2_immlen_offset();
|
||||
ensure!(
|
||||
core_index != 0,
|
||||
"LD cannot be used to move from host to host"
|
||||
);
|
||||
let (r1_val, rd_val) = {
|
||||
let (host, core) = cores.host_and_cores(core_index);
|
||||
let r1_val = core.register(r1);
|
||||
let rd_val = core.register(rd);
|
||||
let r1_val = add_offset_r1(r1_val, offset_select, offset_value);
|
||||
let rd_val = add_offset_rd(rd_val, offset_select, offset_value);
|
||||
let global_memory = host.load::<u8>(r1_val, imm_len)?;
|
||||
core.execute_store(rd_val, global_memory[0])?;
|
||||
(r1_val, rd_val)
|
||||
};
|
||||
cores.provenance_global_load_to_local(core_index as usize, r1_val, rd_val, imm_len as usize);
|
||||
ensure!(core != 0, "LD cannot be used to move from host to host");
|
||||
let (host, core) = cores.host_and_cores(core);
|
||||
let r1_val = core.register(r1);
|
||||
let rd_val = core.register(rd);
|
||||
let r1_val = add_offset_r1(r1_val, offset_select, offset_value);
|
||||
let rd_val = add_offset_rd(rd_val, offset_select, offset_value);
|
||||
let global_memory = host.load::<u8>(r1_val, imm_len)?;
|
||||
core.execute_store(rd_val, global_memory[0])?;
|
||||
TRACER.lock().unwrap().post_ld(cores, data);
|
||||
Ok(InstructionStatus::Completed)
|
||||
}
|
||||
@@ -864,16 +819,13 @@ pub fn st(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus> {
|
||||
let (core, rd, r1, _, imm_len, offset_select, offset_value) =
|
||||
data.get_core_rd_r1_r2_immlen_offset();
|
||||
ensure!(core != 0, "ST cannot be used to move from host to host");
|
||||
let (rd_val, r1_val) = {
|
||||
let core = cores.core(core);
|
||||
let r1_val = core.register(r1);
|
||||
let rd_val = core.register(rd);
|
||||
let r1_val = add_offset_r1(r1_val, offset_select, offset_value);
|
||||
let rd_val = add_offset_rd(rd_val, offset_select, offset_value);
|
||||
(rd_val, r1_val)
|
||||
};
|
||||
cores.store_to_host(core, rd_val, r1_val, imm_len)?;
|
||||
cores.provenance_global_store_from_local(core as usize, rd_val, r1_val, imm_len as usize);
|
||||
let (host, core) = cores.host_and_cores(core);
|
||||
let r1_val = core.register(r1);
|
||||
let rd_val = core.register(rd);
|
||||
let r1_val = add_offset_r1(r1_val, offset_select, offset_value);
|
||||
let rd_val = add_offset_rd(rd_val, offset_select, offset_value);
|
||||
let local_memory = core.load::<u8>(r1_val, imm_len)?;
|
||||
host.execute_store(rd_val, local_memory[0]);
|
||||
TRACER.lock().unwrap().post_st(cores, data);
|
||||
Ok(InstructionStatus::Completed)
|
||||
}
|
||||
@@ -898,9 +850,9 @@ pub fn lldi(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus>
|
||||
#[inline(never)]
|
||||
pub fn lmv(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus> {
|
||||
TRACER.lock().unwrap().pre_lmv(cores, data);
|
||||
let (core_index, rd, r1, _, imm_len, offset_select, offset_value) =
|
||||
let (core, rd, r1, _, imm_len, offset_select, offset_value) =
|
||||
data.get_core_rd_r1_r2_immlen_offset();
|
||||
let core = cores.core(core_index);
|
||||
let core = cores.core(core);
|
||||
let r1_val = core.register(r1);
|
||||
let rd_val = core.register(rd);
|
||||
let r1_val = add_offset_r1(r1_val, offset_select, offset_value);
|
||||
@@ -908,8 +860,6 @@ pub fn lmv(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus>
|
||||
let local_memory = core.load::<u8>(r1_val, imm_len)?;
|
||||
let tmp = local_memory[0].to_vec();
|
||||
core.execute_store(rd_val, tmp.as_slice());
|
||||
let _ = core;
|
||||
cores.provenance_local_copy(core_index as usize, rd_val, r1_val, imm_len as usize, "lmv");
|
||||
TRACER.lock().unwrap().post_lmv(cores, data);
|
||||
Ok(InstructionStatus::Completed)
|
||||
}
|
||||
@@ -931,12 +881,7 @@ pub fn isa_recv(functor: usize) -> bool {
|
||||
|
||||
#[inline(never)]
|
||||
pub fn recv(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus> {
|
||||
Ok(InstructionStatus::Receiving(data))
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
pub fn isa_wait(functor: usize) -> bool {
|
||||
(wait as *const () as usize) == functor
|
||||
Ok(InstructionStatus::Reciving(data))
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
@@ -944,11 +889,6 @@ pub fn wait(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus>
|
||||
Ok(InstructionStatus::Waiting(data))
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
pub fn isa_sync(functor: usize) -> bool {
|
||||
(sync as *const () as usize) == functor
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
pub fn sync(cores: &mut CPU, data: InstructionData) -> Result<InstructionStatus> {
|
||||
Ok(InstructionStatus::Sync(data))
|
||||
|
||||
@@ -22,7 +22,7 @@ pub enum InstructionStatus {
|
||||
Completed,
|
||||
Waiting(InstructionData),
|
||||
Sending(InstructionData),
|
||||
Receiving(InstructionData),
|
||||
Reciving(InstructionData),
|
||||
Sync(InstructionData),
|
||||
#[default]
|
||||
NotExecuted,
|
||||
@@ -59,21 +59,21 @@ pub type Instructions = Vec<Instruction>;
|
||||
pub type InstructionType = fn(&mut CPU, InstructionData) -> Result<InstructionStatus>;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct VectorBitWidth {
|
||||
pub vector_input_bitwidth: usize,
|
||||
pub vector_output_bitwidth: usize,
|
||||
pub struct VectorBitWith {
|
||||
pub vector_input_bitwith: usize,
|
||||
pub vector_output_bitwith: usize,
|
||||
}
|
||||
|
||||
/// Support for the
|
||||
/// setbw ibiw, obiw
|
||||
/// Set the bit-widths of each element for input vectors and output vectors. Related vector instructions
|
||||
/// use the configured bit-widths. Once setbw is called, all subsequent related vector instructions will
|
||||
/// use the configured bit-widths. Once setbw is caled, all subsequent related vector instructions will
|
||||
/// use the configured bit-widths, until a new setbw is called. Once ibiw and obiw are set, ibyw and
|
||||
/// obyw are also set accordingly by the hardware.
|
||||
/// If the hardware does not support variable bit-width, this instruction is invalid and the matrix/vector
|
||||
/// instructions use the fixed bit-width of the hardware.
|
||||
pub struct InstructionsBuilder {
|
||||
vector_bit_width: VectorBitWidth,
|
||||
vector_bit_with: VectorBitWith,
|
||||
instructions: Instructions,
|
||||
}
|
||||
|
||||
@@ -86,9 +86,9 @@ impl Default for InstructionsBuilder {
|
||||
impl InstructionsBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
vector_bit_width: VectorBitWidth {
|
||||
vector_input_bitwidth: 32,
|
||||
vector_output_bitwidth: 32,
|
||||
vector_bit_with: VectorBitWith {
|
||||
vector_input_bitwith: 32,
|
||||
vector_output_bitwith: 32,
|
||||
},
|
||||
instructions: Instructions::new(),
|
||||
}
|
||||
@@ -97,9 +97,9 @@ impl InstructionsBuilder {
|
||||
pub fn make_inst(&mut self, functor: InstructionType, data: InstructionData) {
|
||||
if is_setbw(functor) {
|
||||
let (ibiw, obiw) = data.get_ibiw_obiw();
|
||||
self.vector_bit_width.vector_input_bitwidth =
|
||||
self.vector_bit_with.vector_input_bitwith =
|
||||
ibiw.try_into().expect("ibiw can not be negative");
|
||||
self.vector_bit_width.vector_output_bitwidth =
|
||||
self.vector_bit_with.vector_output_bitwith =
|
||||
obiw.try_into().expect("obiw can not be negative");
|
||||
return;
|
||||
}
|
||||
@@ -107,7 +107,7 @@ impl InstructionsBuilder {
|
||||
if (isa_simd(functor)) {
|
||||
self.instructions.push(Instruction::new(
|
||||
data,
|
||||
dispatch_simd(functor, self.vector_bit_width).unwrap(),
|
||||
dispatch_simd(functor, self.vector_bit_with).unwrap(),
|
||||
))
|
||||
} else {
|
||||
self.instructions.push(Instruction::new(data, functor))
|
||||
|
||||
@@ -601,11 +601,7 @@ fn json_to_wait(
|
||||
inst_data_builder: &mut InstructionDataBuilder,
|
||||
json: &Value,
|
||||
) -> Result<()> {
|
||||
inst_data_builder.set_offset_select_value(
|
||||
json_i64!(json, "event_register") as i32,
|
||||
json_i64!(json, "wait_value") as i32,
|
||||
);
|
||||
inst_builder.make_inst(wait, inst_data_builder.build());
|
||||
todo!("Not present in the compiler");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -614,10 +610,7 @@ fn json_to_sync(
|
||||
inst_data_builder: &mut InstructionDataBuilder,
|
||||
json: &Value,
|
||||
) -> Result<()> {
|
||||
inst_data_builder
|
||||
.set_imm_core(json_i64!(json, "core") as i32 + 1)
|
||||
.set_offset_select_value(json_i64!(json, "event_register") as i32, 0);
|
||||
inst_builder.make_inst(sync, inst_data_builder.build());
|
||||
todo!("Not present in the compiler");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,639 +0,0 @@
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
fs::File,
|
||||
io::{BufWriter, Write},
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Provenance {
|
||||
#[default]
|
||||
Uninitialized,
|
||||
Unknown,
|
||||
Samples(u64),
|
||||
}
|
||||
|
||||
impl Provenance {
|
||||
pub fn sample(sample: u32) -> Self {
|
||||
if sample < 64 {
|
||||
Self::Samples(1_u64 << sample)
|
||||
} else {
|
||||
Self::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
fn merge(self, other: Self) -> Self {
|
||||
match (self, other) {
|
||||
(Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
|
||||
(Self::Uninitialized, value) | (value, Self::Uninitialized) => value,
|
||||
(Self::Samples(left), Self::Samples(right)) => Self::Samples(left | right),
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_all(values: impl IntoIterator<Item = Self>) -> Self {
|
||||
let mut values = values.into_iter();
|
||||
values
|
||||
.next()
|
||||
.map_or(Self::Uninitialized, |first| values.fold(first, Self::merge))
|
||||
}
|
||||
|
||||
fn samples(self) -> Vec<u32> {
|
||||
match self {
|
||||
Self::Samples(mask) => (0..64)
|
||||
.filter(|sample| mask & (1_u64 << sample) != 0)
|
||||
.collect(),
|
||||
Self::Unknown | Self::Uninitialized => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn state(self) -> &'static str {
|
||||
match self {
|
||||
Self::Samples(_) => "known",
|
||||
Self::Unknown => "unknown",
|
||||
Self::Uninitialized => "uninitialized",
|
||||
}
|
||||
}
|
||||
|
||||
fn is_mixed(self) -> bool {
|
||||
matches!(self, Self::Samples(mask) if mask.count_ones() > 1)
|
||||
}
|
||||
|
||||
fn json(self) -> Value {
|
||||
json!({
|
||||
"provenance": self.samples(),
|
||||
"provenance_state": self.state(),
|
||||
"mixed": self.is_mixed(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ExecutionContext {
|
||||
cycle: u64,
|
||||
core: usize,
|
||||
pc: usize,
|
||||
iteration: u32,
|
||||
}
|
||||
|
||||
impl Default for ExecutionContext {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
cycle: 0,
|
||||
core: 0,
|
||||
pc: 0,
|
||||
iteration: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct Writer {
|
||||
version: u64,
|
||||
cycle: u64,
|
||||
core: usize,
|
||||
pc: usize,
|
||||
iteration: u32,
|
||||
provenance: Provenance,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct GlobalCell {
|
||||
provenance: Provenance,
|
||||
writer: Option<Writer>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TraceSink {
|
||||
output: BufWriter<File>,
|
||||
}
|
||||
|
||||
impl TraceSink {
|
||||
fn new(path: impl AsRef<Path>) -> std::io::Result<Self> {
|
||||
let file = File::create(path)?;
|
||||
Ok(Self {
|
||||
output: BufWriter::new(file),
|
||||
})
|
||||
}
|
||||
|
||||
fn event(&mut self, value: Value) {
|
||||
serde_json::to_writer(&mut self.output, &value).expect("write provenance event");
|
||||
self.output
|
||||
.write_all(b"\n")
|
||||
.expect("write provenance newline");
|
||||
}
|
||||
|
||||
fn flush(&mut self) {
|
||||
self.output.flush().expect("flush provenance trace");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProvenanceTracker {
|
||||
global: Vec<GlobalCell>,
|
||||
local: Vec<Vec<Provenance>>,
|
||||
next_version: u64,
|
||||
context: ExecutionContext,
|
||||
sink: Arc<Mutex<TraceSink>>,
|
||||
}
|
||||
|
||||
impl ProvenanceTracker {
|
||||
pub fn new(core_count: usize, path: impl AsRef<Path>) -> std::io::Result<Self> {
|
||||
if let Some(parent) = path.as_ref().parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let sink = Arc::new(Mutex::new(TraceSink::new(path)?));
|
||||
let tracker = Self {
|
||||
global: Vec::new(),
|
||||
local: vec![Vec::new(); core_count],
|
||||
next_version: 0,
|
||||
context: ExecutionContext::default(),
|
||||
sink,
|
||||
};
|
||||
tracker.write(json!({
|
||||
"event": "provenance_trace_start",
|
||||
"schema": 1,
|
||||
"core_count": core_count,
|
||||
}));
|
||||
Ok(tracker)
|
||||
}
|
||||
|
||||
pub fn begin_batch(&mut self, batch_size: usize) {
|
||||
self.global.fill(GlobalCell::default());
|
||||
for memory in &mut self.local {
|
||||
memory.fill(Provenance::Uninitialized);
|
||||
}
|
||||
self.next_version = 0;
|
||||
self.write(json!({
|
||||
"event": "batch_start",
|
||||
"batch_size": batch_size,
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn set_context(&mut self, cycle: u64, core: usize, pc: usize, iteration: u32) {
|
||||
self.context = ExecutionContext {
|
||||
cycle,
|
||||
core,
|
||||
pc,
|
||||
iteration,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn cycle(&self) -> u64 {
|
||||
self.context.cycle
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) {
|
||||
self.sink.lock().unwrap().flush();
|
||||
}
|
||||
|
||||
pub fn schedule_stall(&self, core: usize, remaining_cycles: u64) {
|
||||
self.write(json!({
|
||||
"event": "diagnostic_core_stall",
|
||||
"cycle": self.context.cycle,
|
||||
"core": core,
|
||||
"pc": self.context.pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"remaining_cycles": remaining_cycles,
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn schedule_target_stall(&self, core: usize, pc: usize, remaining_cycles: u64) {
|
||||
self.write(json!({
|
||||
"event": "diagnostic_target_stall",
|
||||
"cycle": self.context.cycle,
|
||||
"core": core,
|
||||
"pc": pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"remaining_cycles": remaining_cycles,
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn schedule_config(
|
||||
&self,
|
||||
policy: &'static str,
|
||||
seed: u64,
|
||||
target: Option<Value>,
|
||||
deferral_budget: u64,
|
||||
fixed_stall: Option<(usize, u64)>,
|
||||
fixed_target_stall: Option<(usize, usize, Option<u32>, u64)>,
|
||||
) {
|
||||
self.write(json!({
|
||||
"event": "scheduler_config",
|
||||
"schedule_policy": policy,
|
||||
"schedule_seed": seed,
|
||||
"target_dependency": target,
|
||||
"deferral_budget": deferral_budget,
|
||||
"fixed_stall": fixed_stall.map(|(core, cycles)| json!({
|
||||
"core": core,
|
||||
"cycles": cycles,
|
||||
})),
|
||||
"fixed_target_stall": fixed_target_stall.map(|(core, pc, iteration, cycles)| json!({
|
||||
"core": core,
|
||||
"pc": pc,
|
||||
"iteration": iteration,
|
||||
"cycles": cycles,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn scheduler_event(&self, event: Value) {
|
||||
self.write(event);
|
||||
}
|
||||
|
||||
fn write(&self, value: Value) {
|
||||
self.sink.lock().unwrap().event(value);
|
||||
}
|
||||
|
||||
fn ensure_global(&mut self, end: usize) {
|
||||
if self.global.len() < end {
|
||||
self.global.resize(end, GlobalCell::default());
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_local(&mut self, core: usize, end: usize) {
|
||||
if let Some(memory) = self.local.get_mut(core)
|
||||
&& memory.len() < end
|
||||
{
|
||||
memory.resize(end, Provenance::Uninitialized);
|
||||
}
|
||||
}
|
||||
|
||||
fn local_tags(&mut self, core: usize, address: usize, size: usize) -> Vec<Provenance> {
|
||||
let Some(end) = address.checked_add(size) else {
|
||||
return vec![Provenance::Unknown; size];
|
||||
};
|
||||
self.ensure_local(core, end);
|
||||
self.local[core][address..end].to_vec()
|
||||
}
|
||||
|
||||
fn store_local_tags(&mut self, core: usize, address: usize, tags: &[Provenance]) {
|
||||
let Some(end) = address.checked_add(tags.len()) else {
|
||||
return;
|
||||
};
|
||||
self.ensure_local(core, end);
|
||||
self.local[core][address..end].copy_from_slice(tags);
|
||||
}
|
||||
|
||||
fn unique_versions(cells: &[GlobalCell]) -> Vec<u64> {
|
||||
cells
|
||||
.iter()
|
||||
.filter_map(|cell| cell.writer.map(|writer| writer.version))
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn unique_writers(cells: &[GlobalCell]) -> Vec<Writer> {
|
||||
cells
|
||||
.iter()
|
||||
.filter_map(|cell| cell.writer)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn writer_json(writer: Writer) -> Value {
|
||||
json!({
|
||||
"version": writer.version,
|
||||
"cycle": writer.cycle,
|
||||
"core": writer.core,
|
||||
"pc": writer.pc,
|
||||
"core_iteration": writer.iteration,
|
||||
"provenance": writer.provenance.samples(),
|
||||
"provenance_state": writer.provenance.state(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn input_store(&mut self, address: usize, size: usize, sample: u32) {
|
||||
let Some(end) = address.checked_add(size) else {
|
||||
return;
|
||||
};
|
||||
self.ensure_global(end);
|
||||
let provenance = Provenance::sample(sample);
|
||||
self.next_version += 1;
|
||||
let writer = Writer {
|
||||
version: self.next_version,
|
||||
cycle: self.context.cycle,
|
||||
core: 0,
|
||||
pc: 0,
|
||||
iteration: sample,
|
||||
provenance,
|
||||
};
|
||||
let overwritten_versions = Self::unique_versions(&self.global[address..end]);
|
||||
for cell in &mut self.global[address..end] {
|
||||
*cell = GlobalCell {
|
||||
provenance,
|
||||
writer: Some(writer),
|
||||
};
|
||||
}
|
||||
let mut event = json!({
|
||||
"event": "external_input_store",
|
||||
"cycle": self.context.cycle,
|
||||
"core": 0,
|
||||
"pc": 0,
|
||||
"core_iteration": sample,
|
||||
"address": address,
|
||||
"size": size,
|
||||
"sample": sample,
|
||||
"version": writer.version,
|
||||
"overwritten_versions": overwritten_versions,
|
||||
});
|
||||
if let Some(object) = event.as_object_mut() {
|
||||
object.extend(provenance.json().as_object().unwrap().clone());
|
||||
}
|
||||
self.write(event);
|
||||
}
|
||||
|
||||
pub fn global_store_from_local(
|
||||
&mut self,
|
||||
core: usize,
|
||||
global_address: usize,
|
||||
local_address: usize,
|
||||
size: usize,
|
||||
) {
|
||||
let Some(end) = global_address.checked_add(size) else {
|
||||
return;
|
||||
};
|
||||
let tags = self.local_tags(core, local_address, size);
|
||||
self.ensure_global(end);
|
||||
self.next_version += 1;
|
||||
let provenance = Provenance::merge_all(tags.iter().copied());
|
||||
let writer = Writer {
|
||||
version: self.next_version,
|
||||
cycle: self.context.cycle,
|
||||
core,
|
||||
pc: self.context.pc,
|
||||
iteration: self.context.iteration,
|
||||
provenance,
|
||||
};
|
||||
let overwritten_versions = Self::unique_versions(&self.global[global_address..end]);
|
||||
let overwritten_writers = Self::unique_writers(&self.global[global_address..end]);
|
||||
for (cell, tag) in self.global[global_address..end].iter_mut().zip(tags) {
|
||||
*cell = GlobalCell {
|
||||
provenance: tag,
|
||||
writer: Some(writer),
|
||||
};
|
||||
}
|
||||
let mut event = json!({
|
||||
"event": "global_store",
|
||||
"cycle": self.context.cycle,
|
||||
"core": core,
|
||||
"pc": self.context.pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"address": global_address,
|
||||
"local_address": local_address,
|
||||
"size": size,
|
||||
"version": writer.version,
|
||||
"overwritten_versions": overwritten_versions,
|
||||
"overwritten_writers": overwritten_writers.into_iter().map(Self::writer_json).collect::<Vec<_>>(),
|
||||
});
|
||||
if let Some(object) = event.as_object_mut() {
|
||||
object.extend(provenance.json().as_object().unwrap().clone());
|
||||
}
|
||||
self.write(event);
|
||||
}
|
||||
|
||||
pub fn global_load_to_local(
|
||||
&mut self,
|
||||
core: usize,
|
||||
global_address: usize,
|
||||
local_address: usize,
|
||||
size: usize,
|
||||
) {
|
||||
let Some(end) = global_address.checked_add(size) else {
|
||||
return;
|
||||
};
|
||||
self.ensure_global(end);
|
||||
let cells = self.global[global_address..end].to_vec();
|
||||
let tags: Vec<_> = cells.iter().map(|cell| cell.provenance).collect();
|
||||
let provenance = Provenance::merge_all(tags.iter().copied());
|
||||
let writers = Self::unique_writers(&cells);
|
||||
let versions = Self::unique_versions(&cells);
|
||||
self.store_local_tags(core, local_address, &tags);
|
||||
let mut event = json!({
|
||||
"event": "global_load",
|
||||
"cycle": self.context.cycle,
|
||||
"core": core,
|
||||
"pc": self.context.pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"address": global_address,
|
||||
"local_address": local_address,
|
||||
"size": size,
|
||||
"versions": versions,
|
||||
"last_writers": writers.into_iter().map(Self::writer_json).collect::<Vec<_>>(),
|
||||
});
|
||||
if let Some(object) = event.as_object_mut() {
|
||||
object.extend(provenance.json().as_object().unwrap().clone());
|
||||
}
|
||||
self.write(event);
|
||||
}
|
||||
|
||||
pub fn local_copy(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
size: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
let tags = self.local_tags(core, source, size);
|
||||
let provenance = Provenance::merge_all(tags.iter().copied());
|
||||
self.store_local_tags(core, destination, &tags);
|
||||
self.local_event(
|
||||
operation,
|
||||
core,
|
||||
destination,
|
||||
size,
|
||||
provenance,
|
||||
&[provenance],
|
||||
);
|
||||
}
|
||||
|
||||
pub fn local_strided_copy(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
element_size: usize,
|
||||
stride: usize,
|
||||
element_count: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
let mut tags = Vec::with_capacity(element_size.saturating_mul(element_count));
|
||||
for index in 0..element_count {
|
||||
let address =
|
||||
source.saturating_add(index.saturating_mul(stride).saturating_mul(element_size));
|
||||
tags.extend(self.local_tags(core, address, element_size));
|
||||
}
|
||||
let provenance = Provenance::merge_all(tags.iter().copied());
|
||||
self.store_local_tags(core, destination, &tags);
|
||||
self.local_event(
|
||||
operation,
|
||||
core,
|
||||
destination,
|
||||
tags.len(),
|
||||
provenance,
|
||||
&[provenance],
|
||||
);
|
||||
}
|
||||
|
||||
pub fn local_transform(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
sources: &[(usize, usize)],
|
||||
output_size: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
let source_tags: Vec<Vec<_>> = sources
|
||||
.iter()
|
||||
.map(|&(address, size)| self.local_tags(core, address, size))
|
||||
.collect();
|
||||
let mut output = Vec::with_capacity(output_size);
|
||||
for index in 0..output_size {
|
||||
let provenance = Provenance::merge_all(
|
||||
source_tags
|
||||
.iter()
|
||||
.filter_map(|tags| tags.get(index).copied()),
|
||||
);
|
||||
output.push(provenance);
|
||||
}
|
||||
let provenance = Provenance::merge_all(output.iter().copied());
|
||||
self.store_local_tags(core, destination, &output);
|
||||
let operands: Vec<_> = source_tags
|
||||
.iter()
|
||||
.map(|tags| Provenance::merge_all(tags.iter().copied()))
|
||||
.collect();
|
||||
self.local_event(
|
||||
operation,
|
||||
core,
|
||||
destination,
|
||||
output_size,
|
||||
provenance,
|
||||
&operands,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn local_broadcast_transform(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
source_size: usize,
|
||||
output_size: usize,
|
||||
operation: &'static str,
|
||||
) {
|
||||
let tags = self.local_tags(core, source, source_size);
|
||||
let provenance = Provenance::merge_all(tags.iter().copied());
|
||||
self.store_local_tags(core, destination, &vec![provenance; output_size]);
|
||||
self.local_event(
|
||||
operation,
|
||||
core,
|
||||
destination,
|
||||
output_size,
|
||||
provenance,
|
||||
&[provenance],
|
||||
);
|
||||
}
|
||||
|
||||
pub fn local_mvm_transform(
|
||||
&mut self,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
source: usize,
|
||||
element_size: usize,
|
||||
output_size: usize,
|
||||
used_rows: &[bool],
|
||||
operation: &'static str,
|
||||
) {
|
||||
let mut provenance = Provenance::Uninitialized;
|
||||
for (row, used) in used_rows.iter().copied().enumerate() {
|
||||
if used {
|
||||
provenance = provenance.merge(Provenance::merge_all(self.local_tags(
|
||||
core,
|
||||
source + row * element_size,
|
||||
element_size,
|
||||
)));
|
||||
}
|
||||
}
|
||||
self.store_local_tags(core, destination, &vec![provenance; output_size]);
|
||||
self.local_event(
|
||||
operation,
|
||||
core,
|
||||
destination,
|
||||
output_size,
|
||||
provenance,
|
||||
&[provenance],
|
||||
);
|
||||
}
|
||||
|
||||
pub fn send_transfer(
|
||||
&mut self,
|
||||
sender: usize,
|
||||
receiver: usize,
|
||||
source: usize,
|
||||
destination: usize,
|
||||
size: usize,
|
||||
) {
|
||||
let tags = self.local_tags(sender, source, size);
|
||||
let provenance = Provenance::merge_all(tags.iter().copied());
|
||||
self.store_local_tags(receiver, destination, &tags);
|
||||
let mut event = json!({
|
||||
"event": "send_recv_transfer",
|
||||
"cycle": self.context.cycle,
|
||||
"pc": self.context.pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"sender_core": sender,
|
||||
"receiver_core": receiver,
|
||||
"source_address": source,
|
||||
"destination_address": destination,
|
||||
"size": size,
|
||||
});
|
||||
if let Some(object) = event.as_object_mut() {
|
||||
object.extend(provenance.json().as_object().unwrap().clone());
|
||||
}
|
||||
self.write(event);
|
||||
}
|
||||
|
||||
fn local_event(
|
||||
&self,
|
||||
operation: &'static str,
|
||||
core: usize,
|
||||
destination: usize,
|
||||
size: usize,
|
||||
provenance: Provenance,
|
||||
operands: &[Provenance],
|
||||
) {
|
||||
let mut event = json!({
|
||||
"event": "local_compute",
|
||||
"operation": operation,
|
||||
"cycle": self.context.cycle,
|
||||
"core": core,
|
||||
"pc": self.context.pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"destination_address": destination,
|
||||
"size": size,
|
||||
"operand_provenance": operands.iter().map(|tag| tag.json()).collect::<Vec<_>>(),
|
||||
});
|
||||
if let Some(object) = event.as_object_mut() {
|
||||
object.extend(provenance.json().as_object().unwrap().clone());
|
||||
}
|
||||
self.write(event);
|
||||
if provenance.is_mixed() {
|
||||
self.write(json!({
|
||||
"event": "cross_sample_data_mix",
|
||||
"cycle": self.context.cycle,
|
||||
"core": core,
|
||||
"pc": self.context.pc,
|
||||
"core_iteration": self.context.iteration,
|
||||
"operation": operation,
|
||||
"destination_address": destination,
|
||||
"size": size,
|
||||
"operand_provenance": operands.iter().map(|tag| tag.json()).collect::<Vec<_>>(),
|
||||
"provenance": provenance.samples(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,10 +33,10 @@ pub struct SendRecv {
|
||||
impl SendRecv {
|
||||
pub fn new(num_core: usize) -> Self {
|
||||
let sending = [Option::None].repeat(num_core);
|
||||
let receiving = [Option::None].repeat(num_core);
|
||||
let reciving = [Option::None].repeat(num_core);
|
||||
Self {
|
||||
sending: sending.into(),
|
||||
receiving: receiving.into(),
|
||||
receiving: reciving.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,27 +73,18 @@ where
|
||||
let data = inst.data;
|
||||
TRACER.lock().unwrap().pre_recv(cpu, data);
|
||||
}
|
||||
{
|
||||
let [sender_core, receiver_core] =
|
||||
cpu.get_multiple_cores([sender.internal_core, receiver.internal_core]);
|
||||
let memory = sender_core
|
||||
.load::<u8>(sender.address, sender.size)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Sender crashed while transferring memory from {} with size {}",
|
||||
sender.address, sender.size
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
receiver_core.execute_store(receiver.address, memory[0]);
|
||||
}
|
||||
cpu.provenance_send_transfer(
|
||||
sender.internal_core,
|
||||
receiver.internal_core,
|
||||
sender.address,
|
||||
receiver.address,
|
||||
sender.size,
|
||||
);
|
||||
let [sender_core, reciver_core] =
|
||||
cpu.get_multiple_cores([sender.internal_core, receiver.internal_core]);
|
||||
let memory = sender_core
|
||||
.load::<u8>(sender.address, sender.size)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Sender crash tranfering memroy from {} with size {}",
|
||||
sender.address, sender.size
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
reciver_core.execute_store(receiver.address, memory[0]);
|
||||
{
|
||||
let sender = &mut core_instructions[sender.internal_core];
|
||||
let pc = sender.program_counter;
|
||||
@@ -133,19 +124,19 @@ where
|
||||
let receiver: usize = imm_core.try_into().expect("imm_core can not be negative");
|
||||
assert_ne!(receiver, 0, "Host can not use receive");
|
||||
send_recv.sending[sender] = Some(SendRecvInfo::new(sender, receiver, address, imm_len));
|
||||
let transferred = transfer_memory(
|
||||
let transfered = transfer_memory(
|
||||
cpu,
|
||||
core_instructions,
|
||||
send_recv.sending[sender],
|
||||
send_recv.receiving[receiver],
|
||||
);
|
||||
if transferred {
|
||||
if transfered {
|
||||
send_recv.sending[sender] = None;
|
||||
send_recv.receiving[receiver] = None;
|
||||
}
|
||||
(transferred, if transferred { receiver } else { 0 })
|
||||
(transfered, receiver)
|
||||
}
|
||||
InstructionStatus::Receiving(instruction_data) => {
|
||||
InstructionStatus::Reciving(instruction_data) => {
|
||||
let (core_idx, imm_core) = instruction_data.get_core_immcore();
|
||||
let rd = instruction_data.rd();
|
||||
let imm_len = instruction_data
|
||||
@@ -162,17 +153,17 @@ where
|
||||
assert_ne!(sender, 0, "Host can not use send");
|
||||
send_recv.receiving[receiver] =
|
||||
Some(SendRecvInfo::new(receiver, sender, address, imm_len));
|
||||
let transferred = transfer_memory(
|
||||
let transfered = transfer_memory(
|
||||
cpu,
|
||||
core_instructions,
|
||||
send_recv.sending[sender],
|
||||
send_recv.receiving[receiver],
|
||||
);
|
||||
if transferred {
|
||||
if transfered {
|
||||
send_recv.sending[sender] = None;
|
||||
send_recv.receiving[receiver] = None;
|
||||
}
|
||||
(transferred, if transferred { sender } else { 0 })
|
||||
(transfered, sender)
|
||||
}
|
||||
_ => (false, 0),
|
||||
}
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
mod common;
|
||||
|
||||
use pimcore::{
|
||||
CoreInstructionsBuilder, Executable,
|
||||
instruction_set::{InstructionsBuilder, instruction_data::InstructionDataBuilder, isa::*},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn restarts_cores_and_loads_each_input() {
|
||||
let cpu = common::empty_cpu(1);
|
||||
let mut cores = CoreInstructionsBuilder::new(1);
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
data.set_core_indx(1).fix_core_indx();
|
||||
instructions.make_inst(sldi, data.set_rdimm(1, 0).build());
|
||||
instructions.make_inst(sldi, data.set_rdimm(2, 0).build());
|
||||
instructions.make_inst(ld, data.set_rdr1(2, 1).set_imm_len(4).build());
|
||||
instructions.make_inst(sldi, data.set_rdimm(3, 4).build());
|
||||
instructions.make_inst(st, data.set_rdr1(3, 2).set_imm_len(4).build());
|
||||
cores.set_core(1, instructions.build());
|
||||
|
||||
let mut executable = Executable::new(cpu, cores.build());
|
||||
let first = 1.0f32.to_ne_bytes();
|
||||
let second = 2.0f32.to_ne_bytes();
|
||||
assert!(
|
||||
executable
|
||||
.execute_batch(&[&first[..3]], &[(0, 4)], &[])
|
||||
.is_err()
|
||||
);
|
||||
executable
|
||||
.execute_batch(&[&first, &second], &[(0, 4)], &[])
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
executable.cpu_mut().host().load::<f32>(4, 4).unwrap()[0],
|
||||
[2.0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_each_iteration_output() {
|
||||
let cpu = common::empty_cpu(1);
|
||||
let mut cores = CoreInstructionsBuilder::new(1);
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
data.set_core_indx(1).fix_core_indx();
|
||||
instructions.make_inst(sldi, data.set_rdimm(1, 0).build());
|
||||
instructions.make_inst(sldi, data.set_rdimm(2, 0).build());
|
||||
instructions.make_inst(ld, data.set_rdr1(2, 1).set_imm_len(4).build());
|
||||
instructions.make_inst(sldi, data.set_rdimm(3, 4).build());
|
||||
instructions.make_inst(st, data.set_rdr1(3, 2).set_imm_len(4).build());
|
||||
cores.set_core(1, instructions.build());
|
||||
|
||||
let mut executable = Executable::new(cpu, cores.build());
|
||||
let first = 1.0f32.to_ne_bytes();
|
||||
let second = 2.0f32.to_ne_bytes();
|
||||
let outputs = executable
|
||||
.execute_batch(&[&first, &second], &[(0, 4)], &[(4, 2), (6, 2)])
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(outputs.len(), 2);
|
||||
assert_eq!(
|
||||
f32::from_ne_bytes(outputs[0].as_slice().try_into().unwrap()),
|
||||
1.0
|
||||
);
|
||||
assert_eq!(
|
||||
f32::from_ne_bytes(outputs[1].as_slice().try_into().unwrap()),
|
||||
2.0
|
||||
);
|
||||
}
|
||||
@@ -295,122 +295,3 @@ fn multiple_send_recv_test() {
|
||||
"send_recv failed to store"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_wait_exact_count_resets_test() {
|
||||
let cpu = common::empty_cpu(2);
|
||||
let mut cores = CoreInstructionsBuilder::new(2);
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
|
||||
data.set_core_indx(1).fix_core_indx();
|
||||
for _ in 0..2 {
|
||||
instructions.make_inst(
|
||||
sync,
|
||||
data.set_imm_core(2).set_offset_select_value(0, 0).build(),
|
||||
);
|
||||
}
|
||||
cores.set_core(1, instructions.build());
|
||||
|
||||
data.set_core_indx(2).fix_core_indx();
|
||||
instructions.make_inst(wait, data.set_offset_select_value(0, 2).build());
|
||||
cores.set_core(2, instructions.build());
|
||||
|
||||
Executable::new(cpu, cores.build()).execute().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_wait_rejects_overshoot() {
|
||||
let cpu = common::empty_cpu(3);
|
||||
let mut cores = CoreInstructionsBuilder::new(3);
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
|
||||
data.set_core_indx(1).fix_core_indx();
|
||||
instructions.make_inst(
|
||||
sync,
|
||||
data.set_imm_core(3).set_offset_select_value(0, 0).build(),
|
||||
);
|
||||
cores.set_core(1, instructions.build());
|
||||
|
||||
data.set_core_indx(2).fix_core_indx();
|
||||
instructions.make_inst(
|
||||
sync,
|
||||
data.set_imm_core(3).set_offset_select_value(0, 0).build(),
|
||||
);
|
||||
cores.set_core(2, instructions.build());
|
||||
|
||||
data.set_core_indx(3).fix_core_indx();
|
||||
instructions.make_inst(wait, data.set_offset_select_value(0, 1).build());
|
||||
cores.set_core(3, instructions.build());
|
||||
|
||||
let error = Executable::new(cpu, cores.build()).execute().unwrap_err();
|
||||
assert!(error.to_string().contains("overshot exact value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_wait_deadlock_cycle_is_reported() {
|
||||
let cpu = common::empty_cpu(2);
|
||||
let mut cores = CoreInstructionsBuilder::new(2);
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
|
||||
data.set_core_indx(1).fix_core_indx();
|
||||
instructions.make_inst(wait, data.set_offset_select_value(0, 1).build());
|
||||
instructions.make_inst(
|
||||
sync,
|
||||
data.set_imm_core(2).set_offset_select_value(0, 0).build(),
|
||||
);
|
||||
cores.set_core(1, instructions.build());
|
||||
|
||||
data.set_core_indx(2).fix_core_indx();
|
||||
instructions.make_inst(wait, data.set_offset_select_value(0, 1).build());
|
||||
instructions.make_inst(
|
||||
sync,
|
||||
data.set_imm_core(1).set_offset_select_value(0, 0).build(),
|
||||
);
|
||||
cores.set_core(2, instructions.build());
|
||||
|
||||
let error = Executable::new(cpu, cores.build()).execute().unwrap_err();
|
||||
assert!(error.to_string().contains("wait event"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_transfers_do_not_starve_sync_producer() {
|
||||
let cpu = common::empty_cpu(4);
|
||||
let mut cores = CoreInstructionsBuilder::new(4);
|
||||
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
data.set_core_indx(1).fix_core_indx();
|
||||
instructions.make_inst(sldi, data.set_rdimm(1, 0).build());
|
||||
instructions.make_inst(recv, data.set_rd(1).set_imm_core(2).set_imm_len(1).build());
|
||||
instructions.make_inst(send, data.set_r1(1).set_imm_core(3).set_imm_len(1).build());
|
||||
cores.set_core(1, instructions.build());
|
||||
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
data.set_core_indx(2).fix_core_indx();
|
||||
instructions.make_inst(sldi, data.set_rdimm(1, 0).build());
|
||||
instructions.make_inst(wait, data.set_offset_select_value(0, 1).build());
|
||||
instructions.make_inst(send, data.set_r1(1).set_imm_core(1).set_imm_len(1).build());
|
||||
cores.set_core(2, instructions.build());
|
||||
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
data.set_core_indx(3).fix_core_indx();
|
||||
instructions.make_inst(sldi, data.set_rdimm(1, 0).build());
|
||||
instructions.make_inst(recv, data.set_rd(1).set_imm_core(1).set_imm_len(1).build());
|
||||
cores.set_core(3, instructions.build());
|
||||
|
||||
let mut instructions = InstructionsBuilder::new();
|
||||
let mut data = InstructionDataBuilder::new();
|
||||
data.set_core_indx(4).fix_core_indx();
|
||||
instructions.make_inst(
|
||||
sync,
|
||||
data.set_imm_core(2).set_offset_select_value(0, 0).build(),
|
||||
);
|
||||
cores.set_core(4, instructions.build());
|
||||
|
||||
Executable::new(cpu, cores.build()).execute().unwrap();
|
||||
}
|
||||
|
||||
Submodule backend-simulators/pim/pimsim-nn updated: 17e37c15da...0d03316df4
@@ -1,41 +0,0 @@
|
||||
# Raptor documentation
|
||||
|
||||
Start with the [build and quick start](../README.md). Commands in these guides
|
||||
run from the repository root unless stated otherwise.
|
||||
|
||||
## Compiler
|
||||
|
||||
- [Searchable Spatial and PIM operation reference](dialects/index.html) (open locally in a browser)
|
||||
- [Convolution and GEMM visual guide](lowering-visuals/im2col-story/index.html) (explicit-im2col family)
|
||||
- [Architecture, compilation pipeline, source layout, and simulator tests](compiler/architecture.md)
|
||||
- [Pim compiler options and defaults](compiler/options.md)
|
||||
- [Spatial physical layouts and compatibility matrix](compiler/spatial-layouts.md)
|
||||
- [Scheduling ownership, costs, capacity, and complexity](compiler/scheduling.md)
|
||||
- [Scheduling implementation contracts and model limitations](compiler/scheduling-implementation.md)
|
||||
|
||||
## Evaluation
|
||||
|
||||
- [Measurement methodology and canonical result datasets](evaluation/methodology.md)
|
||||
- [Pimcomp operation support, standalone reproduction, and GA controls](evaluation/pimcomp-reproducibility.md)
|
||||
- [Validation commands and defaults](../validation/README.md)
|
||||
- [Pimcomp comparison and plotting](../validation/tools/pim/pimcomp/compare/README.md)
|
||||
- [Raptor ablation and plotting](../validation/tools/pim/ablation/README.md)
|
||||
- [Pimcomp correctness experiments](../validation/tools/pim/pimcomp/correctness/README.md)
|
||||
|
||||
## Component references
|
||||
|
||||
- [Operation suite](../validation/operations/README.md) and [all 177 cases](../validation/operations/INVENTORY.md)
|
||||
- [Comparison models, provenance, checksums, and hardware profiles](../validation/networks/pimcomp_models/README.md)
|
||||
- [Graph Explorer usage](../tools/raptor_graph_explorer/README.md) and [architecture/API](../tools/raptor_graph_explorer/ARCHITECTURE.md)
|
||||
|
||||
## Normative engineering contracts
|
||||
|
||||
These contracts stay in `.agents/invariants/`; general documentation links to
|
||||
them rather than restating their requirements:
|
||||
|
||||
- [Graph compute batch fragments](../.agents/invariants/GRAPH_COMPUTE_BATCH_INVARIANT.md)
|
||||
- [Compiler performance](../.agents/invariants/PERFORMANCE_OPTIMIZATION_INVARIANT.md)
|
||||
- [Pimsim performance oracle](../.agents/invariants/PIMSIM_NN_ORACLE_INVARIANT.md)
|
||||
- [PIM synchronization](../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md)
|
||||
- [Pipeline scheduling](../.agents/invariants/PIPELINE_SCHEDULING_INVARIANT.md)
|
||||
- [Spatial target generality](../.agents/invariants/SPATIAL_TARGET_GENERALITY_INVARIANT.md)
|
||||
@@ -1,51 +0,0 @@
|
||||
# Compiler architecture and pipeline
|
||||
|
||||
See the [documentation index](../README.md) for related compiler and evaluation
|
||||
references. Source paths below are relative to the repository root.
|
||||
|
||||
## Compilation pipeline
|
||||
|
||||
```text
|
||||
ONNX-MLIR -> Spatial -> Pim (tensor) -> Pim (bufferized) -> Pim artifacts
|
||||
```
|
||||
|
||||
| Stage | Responsibility and source |
|
||||
|---|---|
|
||||
| ONNX → Spatial | Operation lowering, target-neutral layout planning, and plan materialization in `src/PIM/Conversion/ONNXToSpatial`. |
|
||||
| Spatial scheduling | Graph merging, scheduling, verification, and communication realization in `src/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes`; see [scheduling ownership](scheduling.md). |
|
||||
| Spatial → Pim | Cores, communication, packing, and global tensors in `src/PIM/Conversion/SpatialToPim`. |
|
||||
| Bufferization | Writable destinations, one-shot analysis, memory normalization, and verification in `src/PIM/Dialect/Pim/Passes/Transforms/Bufferization`. |
|
||||
| Local-memory planning | Whole-core lifetimes and address reuse in `src/PIM/Dialect/Pim/Passes/Transforms/LocalMemoryPlanning`. |
|
||||
| Verification/codegen | Verify the explicit memory plan and emit artifacts in `src/PIM/Passes/PimCodegen` and `src/PIM/Compiler`. |
|
||||
|
||||
Spatial plans select physical layouts and insert explicit materializations at
|
||||
boundaries. Dense NCHW is the default; compatible operations can use row-strip
|
||||
layouts, while Flatten can reassemble fragmented inputs. Function results
|
||||
remain dense NCHW. See the [layout compatibility reference](spatial-layouts.md)
|
||||
for operation alternatives, legality checks, and planner behavior.
|
||||
|
||||
## Validation and tests
|
||||
|
||||
[Validation instructions](../../validation/README.md) cover ONNX-MLIR reference
|
||||
comparison, functional simulation, performance measurement, and artifacts.
|
||||
The Rust functional simulator reads Raptor's artifact directory;
|
||||
`pimsim-nn` supplies latency, power, and energy estimates.
|
||||
|
||||
```bash
|
||||
cd backend-simulators/pim/pim-simulator
|
||||
cargo test
|
||||
```
|
||||
|
||||
## Repository layout
|
||||
|
||||
- `src/PIM/`: accelerator, dialects, conversions, analyses, and codegen.
|
||||
- `test/PIM/`: compiler unit tests.
|
||||
- `validation/`: operation/network suites and simulator configuration.
|
||||
- `backend-simulators/pim/pim-simulator/`: Rust functional simulator.
|
||||
- `backend-simulators/pim/pimsim-nn/`: performance simulator submodule.
|
||||
- `tools/raptor_graph_explorer/`: [Spatial CSV viewer](../../tools/raptor_graph_explorer/README.md).
|
||||
- `pimcomp_utils/`: comparison helpers containing local paths.
|
||||
- `.github/`: CI build and validation setup.
|
||||
|
||||
CMake exposes `src/PIM` and `test/PIM` through generated shims under
|
||||
`onnx-mlir/src/Accelerators/PIM` and `onnx-mlir/test/accelerators/PIM`.
|
||||
@@ -1,30 +0,0 @@
|
||||
# Pim compiler options
|
||||
|
||||
See the [quick start](../../README.md#compile-a-model) for a complete command
|
||||
and the [documentation index](../README.md) for the compilation pipeline.
|
||||
|
||||
Pass these to `onnx-mlir`; `--help` also lists inherited ONNX-MLIR options.
|
||||
Boolean switches default to off unless stated otherwise.
|
||||
|
||||
| Option | Purpose / default |
|
||||
|---|---|
|
||||
| `--maccel=PIM` | Select the PIM accelerator. |
|
||||
| `--EmitSpatial`, `--EmitPim`, `--EmitPimBufferized`, `--EmitPimCodegen` | Stop at a pipeline stage; default: codegen. |
|
||||
| `--core-count=N`, `--crossbar-size=N`, `--crossbar-count=N` | Required hardware resources; crossbars are square. |
|
||||
| `--pipeline=N\|auto` | Default: 1 (latency PEFT). N > 1 requires exactly N nonempty compute stages. `auto` compares stage counts with static queue-aware throughput costs. Auto requires final codegen; numeric intermediate targets use the initialized schedule. |
|
||||
| `--pim-target-config=PATH` | Target cost/topology configuration; resources must match hardware flags. Default: built-in model. |
|
||||
| `--pim-memory-report=summary\|none` | Memory report at `reports/memory_report.txt`; default: `summary`. |
|
||||
| `--pim-only-codegen` | Run the codegen tail on bufferized Pim IR. |
|
||||
| `--pim-emit-json` | Also emit per-core JSON instructions. |
|
||||
| `--pim-dump-ir` | Write diagnostic IR snapshots with elided large constants; default: off. |
|
||||
| `--pim-periodic-diagnostics` | Write optional recurrence and Spatial execution-work reports; default: off. |
|
||||
| `--pim-export-spatial-dataflow=none\|spatial1\|spatial2\|spatial3\|spatial4\|all` | Export graph, trivially merged, scheduled, and realized CSV snapshots under `reports/`; default: `none`. |
|
||||
| `--pim-conv-lowering=STRATEGY` | `auto` (default), `legacy`, `depthwise`, `packed-im2col`, `streamed-patch`, `streamed-packed`, `output-channel-tiled`, `input-k-tiled`, or `tiled-2d`. |
|
||||
| `--pim-conv-im2col-max-elements=N` | Global im2col limit before streaming; default: 1048576. |
|
||||
| `--pim-conv-stream-chunk-positions=N` | Output positions per streamed chunk; default: 1024. |
|
||||
| `--pim-report-conv-lowering=true\|false` | Bounded lowering report; default: true. |
|
||||
| `--pim-disable-spatial-planning` | Choose each plan's first dense alternative; ONNX rewrites and graph merging remain enabled. |
|
||||
| `--pim-disable-synchronization` | Keep the normal selected schedule and omit wait/sync during code generation. Report a separate zero-cost synchronization estimate for ablation. Removes correctness guarantees for buffer reuse and restart. |
|
||||
| `--pim-detect-communication-deadlock` | Check expanded blocking send/receive ordering. |
|
||||
| `--pim-verify-bufferization-copy-freedom` | Run the expensive pre-bufferization copy-freedom proof. |
|
||||
|
||||
@@ -1,278 +0,0 @@
|
||||
# Scheduling implementation notes
|
||||
|
||||
The [scheduling overview](scheduling.md) maps ownership and summarizes costs/complexity.
|
||||
Normative graph, pipeline, synchronization, and target contracts are linked
|
||||
there; the details below describe current implementation choices.
|
||||
|
||||
## Publication, order, and local materialization
|
||||
|
||||
Deferred transfer planning allocates one host slot for repeated full-fragment
|
||||
requirements with the same physical producer, payload type, and source slot.
|
||||
One immutable producer result identifies one logical inference generation.
|
||||
Scalar source projections retain separate publications until their exact
|
||||
geometry has a common representation in both analyses.
|
||||
|
||||
Boundary planning moves a shared publication's notifications to its earliest
|
||||
existing send boundary. The first notification stores the payload before READY;
|
||||
later notifications emit READY only. Each reader retains its load and READY
|
||||
count. FREE planning includes every physical reader before the first overwrite
|
||||
of the shared slot. Existing unique writer-reader releases, register allocation,
|
||||
capacity-driven FREE-group merging, and restart barriers remain in force.
|
||||
|
||||
Host-slot allocation and shared-boundary planning take expected linear time
|
||||
and space in the number of physical consumer transfers. Structured send runs
|
||||
retain compact per-lane store flags. They do not duplicate payload shaping
|
||||
for notification-only readers.
|
||||
|
||||
[`materializeScheduledCompute`](../../src/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/ScheduledComputeMaterialization.cpp) records
|
||||
graph IDs for publication identity, not execution order. Class lanes retain
|
||||
graph encounter order independently of physical core IDs, preserving regular
|
||||
source-lane mappings. Within each core, instances sort by verified scheduler
|
||||
slots. Only consecutive compatible instances form homogeneous runs; class-lane
|
||||
ordering must not reorder a core's work.
|
||||
|
||||
`insertLocalFragment` replaces a complete singleton insertion with a leading
|
||||
unit-dimension reshape view only when:
|
||||
|
||||
- source and destination have static shapes;
|
||||
- destination rank is source rank + 1, with leading dimension 1 and remaining
|
||||
dimensions exactly equal to the source shape;
|
||||
- element type and encoding match;
|
||||
- offset/size/stride lists all match destination rank; and
|
||||
- every offset is statically zero, every size is the full corresponding
|
||||
destination dimension, and every stride is statically one.
|
||||
|
||||
This includes scalar sources. Other insertions retain `tensor.insert_slice`
|
||||
semantics rather than being converted into views.
|
||||
|
||||
Receive forwarding belongs to
|
||||
[`PimBufferizationPass.cpp`](../../src/PIM/Dialect/Pim/Passes/Transforms/Bufferization/PimBufferizationPass.cpp),
|
||||
after copy lowering and contiguity normalization. It requires a private
|
||||
allocation and single-use receive/copy chain in the same block, zero source and
|
||||
receive offsets, and equal sizes. The receive can sink to the copy target past
|
||||
memory-effect-free operations and `memref.load` (including lane lookup loads).
|
||||
Writes, synchronization, and other effectful operations are barriers. Forwarding
|
||||
does not establish synchronization policy.
|
||||
|
||||
## Transfer accounting and transpose costs
|
||||
|
||||
[`ComputeGraph.cpp`](../../src/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ComputeGraph.cpp) uses the same cached publication map for
|
||||
dependency extraction and projected transfer volume. Physical slots map back
|
||||
to graph lanes; graph-range overlap is not a byte estimate. Blueprint edges
|
||||
belong to this shared graph for both scheduling strategies.
|
||||
|
||||
Exact projections charge selected physical fragments individually, including
|
||||
each fragment's byte, endpoint-memory, and packet rounding. Conservative batch
|
||||
dependencies charge a producer chunk as one aggregate: scale element count by
|
||||
chunk lanes, multiply by effective bitwidth, then round to bytes once before
|
||||
memory-access/flit rounding. Dividing an already rounded whole-result byte
|
||||
count would lose sub-byte payloads. These two granularities are deliberate.
|
||||
Spatial can analyze sub-byte storage; PIM communication lowering requires
|
||||
byte-sized elements. Blueprint assembly charges per fragment. A full fragment
|
||||
receive directly into assembly storage omits duplicate endpoint-memory edge
|
||||
cost; later copy elimination can leave this estimate conservative.
|
||||
|
||||
`CopyAccessPlan` shares ordered contiguous-run geometry between projection
|
||||
costing and PIM copy normalization. Its inputs are a logical copy shape and
|
||||
proven source and destination strides, in elements. The immutable result keeps
|
||||
outer dimensions, run count, run length, and relative offsets compact. Building
|
||||
the plan takes linear time and space in rank, independent of loop trip counts.
|
||||
It creates no IR and does not prove aliasing, storage ownership, or copy legality.
|
||||
PIM bufferization still owns those decisions and the mapping to byte accesses.
|
||||
The plan alone does not describe a complete scheduled memory-request stream.
|
||||
Construction rejects an unrepresentable maximum relative element offset,
|
||||
including the last element of each run. Callers still check byte scaling and
|
||||
base-address addition.
|
||||
Projection costing uses checked row-major strides. Unsupported flattened
|
||||
offsets or strides produce at most one warning per graph cost query. The query
|
||||
uses one separately rounded request per element as a conservative service bound.
|
||||
It does not reject otherwise valid Spatial IR. Target lowering retains its own
|
||||
address and layout legality checks. Unsupported estimates and malformed IR are
|
||||
different conditions.
|
||||
|
||||
The PIM adapter's `planComputeInputMaterialization` reads scheduled Spatial
|
||||
regions without changing them. It returns `Unused`, `ForwardConstant`,
|
||||
`ForwardFunctionInput`, or `CopyAtEntry`. Function-input normalization forwards
|
||||
host inputs into compute bodies before entry-copy materialization.
|
||||
Single-core lowering forwards used arithmetic constants. Batch lowering copies
|
||||
remaining inputs at body entry, including constants. Lowering and costing
|
||||
consume the same decisions. The query has constant time and space per
|
||||
input and does not expand lanes or loops. Abstract target work extraction uses
|
||||
the same query. Subsequent canonicalization can remove uses.
|
||||
`getReusableOutputTensor` shares read-only destination selection with vector
|
||||
lowering. It identifies a tensor operand or requires fresh storage. It does not
|
||||
prove a physical alias, assign an address, or replace one-shot bufferization.
|
||||
The result is valid only for the current SSA graph. Changes to uses, operation
|
||||
order, loop yields, or operands require recomputation. Lowering consumes this
|
||||
decision immediately; it does not cache values across rewrites. Current PIM
|
||||
bufferization consumes the explicit destination ties introduced by target
|
||||
lowering. Output-copy forwarding also consumes the resulting allocation,
|
||||
subview, copy, and dominance facts. An early destination choice alone cannot
|
||||
describe those physical aliases or the final storage lifetimes.
|
||||
Logical storage identity and physical address equality are different facts.
|
||||
Local-memory planning can assign the same address to distinct allocations whose
|
||||
lifetimes do not overlap. Scalar register setup therefore needs placement and
|
||||
instruction-order information in addition to logical alias relationships.
|
||||
Abstract cost estimates need not reconstruct these addresses.
|
||||
|
||||
This input plan does not count physical constant loads. A forwarded host
|
||||
constant can need a new local buffer at each use. Bufferization, host folding,
|
||||
alias analysis, and memory normalization determine the resulting requests.
|
||||
`isZeroBitPatternSplat` shares constant-content classification between graph
|
||||
accounting and code generation. PIM replaces eligible positive-zero and integer-zero
|
||||
loads with local fills. Negative floating zero retains its distinct bit pattern.
|
||||
Constant content is candidate-independent; input placement and buffer reuse
|
||||
depend on the realized candidate. Production uses these shared decisions when
|
||||
extracting Spatial execution events for the queue estimate.
|
||||
|
||||
Execution transpose costs share `getTransposeRun` with lowering: round memory
|
||||
reads/writes per run and add vector execution when source stride is not one.
|
||||
The [Pimsim vector unit](../../backend-simulators/pim/pimsim-nn/src/core/component/VectorUnit.cpp)
|
||||
charges vector payload bytes, not the full strided address footprint. The
|
||||
compiler model follows that accounting; instruction setup/issue and contention
|
||||
remain approximations, not extra inferred memory traffic.
|
||||
|
||||
## Priorities, placement, and recovery limits
|
||||
|
||||
[`PipelineScheduling.cpp`](../../src/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PipelineScheduling.cpp) caches a per-template
|
||||
adjustment between physical execution cost and nominal volume priority, scaling
|
||||
it by chunk lanes. Initialization uses nominal priorities; transposes count as
|
||||
bulk moves there. One joint prefix/resource DP constructs the initial partition.
|
||||
Bounded incumbent/frontier refinement changes partitions and core allocations together.
|
||||
Numeric depths require exactly that many nonempty compute stages throughout both DPs,
|
||||
packing, refinement, and realization. Auto uses the same optimizer across a bounded
|
||||
stage-count domain; all depths share the queue-evaluation budget.
|
||||
Queue-aware Spatial evaluation scores every admitted physical placement. PEFT,
|
||||
final schedule evaluation, and reported per-core demand use physical estimates.
|
||||
These quantities must not be substituted for measured simulator periods.
|
||||
|
||||
Placement compares maximum per-core serial compute plus incident same-stage
|
||||
transfer demand, then completion/span and compute load. Each participating core
|
||||
is charged incident transfer demand as a placement proxy; those charges are not
|
||||
summed twice into elapsed time. Within 1% demand difference, span breaks the tie.
|
||||
Ordered packing plus dependency-tail priority biases cuts away from long
|
||||
dependent groups; it is not a throughput prediction. Measured simulator periods
|
||||
remain authoritative, including when a proxy improves.
|
||||
|
||||
Core budgets come from stage allocation and bounded capacity recovery. Failed
|
||||
packing budgets are not lower bounds. [PEFT reservations](../../src/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PeftScheduler.cpp)
|
||||
prefer weight reuse when distinct weights exceed half the fleet's one-copy
|
||||
resident capacity; otherwise they favor communication/load. The reuse-first
|
||||
constructor supplies feasibility recovery without replacing a successful
|
||||
reservation, and can concentrate work. No exact combinatorial solver proves
|
||||
infeasibility after heuristic failure.
|
||||
|
||||
[`ResidentWeightPacking.hpp`](../../src/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ResidentWeightPacking.hpp) adds at most 17
|
||||
constructions after initial failure: one reverse traversal, then up to 16
|
||||
single-choice replays sharing 65,536 candidate checks. Scratch buffers are reused;
|
||||
an extra `O(T)` failed-assignment snapshot is created only after both initial
|
||||
orders fail. Weight indexing still has `O(R W)` worst-case equality work; partition
|
||||
DP and latency insertion-gap searches remain superlinear as listed in the
|
||||
scheduling overview. Cached PEFT center distances avoid a topology scan per task/candidate;
|
||||
projection and priority analyses share/cache work rather than revisiting every
|
||||
template body per chunk. Ready-transfer signature searches remain another
|
||||
potential compile-time hotspot.
|
||||
|
||||
### Spatial execution costs
|
||||
|
||||
`SchedulingTarget::estimateRealizedScheduleCost` is a read-only query on realized Spatial IR.
|
||||
The PIM adapter extracts compact ordered execution events without constructing PIM operations.
|
||||
It uses physical core assignments, communication, input-materialization decisions, and shared copy geometry.
|
||||
No physical buffer addresses are required.
|
||||
The shared engine models controller arbitration, source FIFOs, synchronization, and repeated generations.
|
||||
Both arbitration policies are sensitivity checks, not guaranteed bounds.
|
||||
The engine returns typed intervals and recurrence evidence before diagnostic serialization.
|
||||
The target adapter adds static lowering support. Spatial owns the selection policy margin.
|
||||
JSON fields are report output and do not control availability or eligibility.
|
||||
Typed evaluation completes before reporting. Serialization never runs queue analysis.
|
||||
Only optional diagnostics construct fingerprints, traces, and per-core resource reports.
|
||||
|
||||
Normal compilation extracts costs for multiple candidates and lowers only the selected schedule.
|
||||
A single candidate bypasses the cost query entirely.
|
||||
Candidate summaries distinguish available timing, static lowering support, and proved modeled recurrence.
|
||||
Unknown support remains explicit. All candidates must satisfy these checks before comparison.
|
||||
`Unsupported` identifies a known static violation, including invalid or repeated physical-core assignments.
|
||||
`Unknown` identifies missing evidence or an unmodeled form, rather than a proven backend rejection.
|
||||
`Supported` covers checked static forms and does not prove final allocation success.
|
||||
A finite interval alone does not establish eligibility.
|
||||
|
||||
Preflight does not repeat bufferization or allocation.
|
||||
The backend owns final legality and signed 32-bit local-memory address validation.
|
||||
Resource failures marked by that owner permit an explicit retry from the original checkpoint.
|
||||
Unclassified failures stop compilation. Every attempted schedule and cause appears in the selection report.
|
||||
|
||||
### Complete-state recurrence
|
||||
|
||||
Queue analysis checks translated states at one fixed core's body entry.
|
||||
Snapshots contain completion counts relative to core entry, ready-input counts, and busy state for every event.
|
||||
Run-length encoding keeps these records compact.
|
||||
Snapshots also contain pending events in arbitration order, remaining FIFO tokens, controller availability, and the tie policy.
|
||||
One pending firing per event makes node IDs sufficient to resolve simultaneous-event ties.
|
||||
The graph and target parameters remain fixed within each query.
|
||||
Time offsets use checked unsigned differences.
|
||||
Equal states require equal positive generation progress on every core.
|
||||
This proves recurrence for the deterministic abstract model, not physical execution-time accuracy.
|
||||
Reporting counters and analysis budgets are not hardware state.
|
||||
|
||||
Token initialization distances and graph edges remain immutable within a query.
|
||||
Consumption clears a drained queue and resets its head immediately.
|
||||
Drained and never-populated queues therefore have the same readiness state.
|
||||
Consumed prefixes, capacities, and compaction indices cannot affect future timing or FIFO contents.
|
||||
An idle controller's past completion cannot delay future arrivals.
|
||||
These normalizations require causal, monotonic transitions, which the proof checks.
|
||||
|
||||
Proof construction uses at most 1024 generations and 64 MiB of snapshot storage.
|
||||
Each checkpoint scans events, dependencies, and remaining tokens, then orders a copy of the pending frontier.
|
||||
Exact comparisons use bounded history; hashes only filter comparisons.
|
||||
Unproved recurrence remains explicit and cannot guide multi-candidate selection.
|
||||
When recurrence is proved, its interval is authoritative for that arbitration policy and its report.
|
||||
Proof-mode reports retain interval-window results under `legacy_interval_window`.
|
||||
Normal costing stops once recurrence is proved. Detailed diagnostics can continue to collect interval-window evidence.
|
||||
A legacy event or generation limit cannot override a later complete-state proof.
|
||||
Budget limits, lack of ready events, and unproved recurrence remain separate evidence.
|
||||
Internal diagnostic queries can cap interval-window work without reducing the recurrence proof budget.
|
||||
The standalone instruction diagnostic keeps its interval-window behavior when recurrence is not requested.
|
||||
|
||||
### Approximation and diagnostics
|
||||
|
||||
Scalar setup, copy forwarding, local reuse, and host-slice folding can change request readiness.
|
||||
These effects remain prediction limitations. Physical address reuse itself adds no execution work.
|
||||
Direct returns use the same return-operand test as lowering and preserve output multiplicity.
|
||||
Captured weights used by vector operations require host loads.
|
||||
Publication-only slices of compact results use `CopyAccessPlan` runs without an intermediate copy.
|
||||
Matrix writeback requires complete aligned array groups.
|
||||
Partial output groups, encoded layouts, unavailable geometry, and indirect output collection produce unavailable costs.
|
||||
|
||||
`--pim-periodic-diagnostics` adds resource summaries and ordered-request fingerprints.
|
||||
Normal compilation creates no fingerprints, detailed traces, or sensitivity runs.
|
||||
Optional local-copy sensitivity removes modeled copy work without changing generated code.
|
||||
It does not describe a legal transformed program or an interval bound.
|
||||
The standalone instruction diagnostic remains available for offline timing validation.
|
||||
|
||||
Checked arithmetic rejects unrepresentable sizes, loop bounds, repeated work, and service durations.
|
||||
Work-only repeats remain compact. Immutable summaries are cached within a query.
|
||||
Ordered memory and communication occurrences expand within the event budget.
|
||||
For `P` compact records, `R` expanded events, and `D` dependencies, construction costs `O(P+R+D)` time.
|
||||
With `B` processed events and `T` token propagations, queue evaluation costs `O(B log R+T)` time.
|
||||
Storage costs `O(P+R+G D)` for bounded generation count `G`, plus bounded recurrence history.
|
||||
Reports separate extraction, expansion, and queue-analysis times.
|
||||
Fingerprints compare memory and blocking-operation order, without addresses or work between requests.
|
||||
Equal fingerprints therefore do not prove equal request readiness or timing.
|
||||
|
||||
### Shared automatic-depth initialization
|
||||
|
||||
`PipelinePartitionTable` owns the ordered segment costs and joint prefix/resource
|
||||
states. Automatic depth shares integer-core segment curves across its depth
|
||||
initializations. Each depth samples its original bounded resource grid.
|
||||
Its reserved-core count changes that grid, so identical DP states are not available across depths.
|
||||
Both modes use the same recurrence, legality checks, and constructive packing
|
||||
implementation.
|
||||
Ordered cost curves share threshold scans. Scalar queries retain their original
|
||||
cost and placement decisions. Compact plans retain the constructive core count
|
||||
before spare cores are assigned. Minimum-resource completion uses the same
|
||||
shared scalar-equivalent curves.
|
||||
|
||||
Automatic-depth initialization reports separate grouping, segment packing,
|
||||
DP-state evaluation, and physical placement. Fixed-depth initialization remains
|
||||
inside the candidate-generation timing. The complete queue model determines
|
||||
eligibility and final selection. Initialization priorities are search costs, not timing bounds.
|
||||
@@ -1,551 +0,0 @@
|
||||
# Spatial scheduling
|
||||
|
||||
`prepareSpatialSchedules` constructs the shared `ComputeGraph`. Latency mode
|
||||
uses PEFT. For `--pipeline > 1` or `--pipeline=auto`, the PIM compiler selects among bounded pipeline
|
||||
candidates with static queue-aware Spatial execution analysis. Pipeline mode does not run PEFT.
|
||||
|
||||
See [implementation notes](scheduling-implementation.md) for fragment-view eligibility,
|
||||
receive forwarding, transfer rounding, cost-model boundaries, and recovery limits.
|
||||
|
||||
## Ownership
|
||||
|
||||
| Responsibility | Owner |
|
||||
|---|---|
|
||||
| Instances, dependencies, execution/transfer costs, resident weights | `ComputeGraph`, `ComputeInstanceUtils` |
|
||||
| Target resources and physical link costs | Compiler target adapter via `SchedulingTarget` |
|
||||
| Latency priorities, reservations, placement, per-core order | `PeftScheduler` |
|
||||
| Capacity-driven workload splitting | `PipelineWorkloadPreparation` |
|
||||
| Groups, stage partitioning, core budgets | `buildPipelineGroups`, `initialPipelinePartition`, `optimizePipelineSchedule` |
|
||||
| Topology clustering and stage-local packing | `PipelineCoreLayout`, `packPipelineStages`, `IndexedResidentWeights` |
|
||||
| Timing evaluation and publication equivalence | `evaluateSchedule`, `populateScheduleEquivalenceClasses` |
|
||||
| Selected execution order and homogeneous runs | Scheduled compute planning/materialization |
|
||||
| Routing, forwarding, blocking communication order | Deferred transfer planning and communication scheduling |
|
||||
| READY/FREE counts, registers, overwrite/restart boundaries | Deferred boundary planning/realization |
|
||||
|
||||
Both strategies produce `MergeScheduleResult`: core assignments, contiguous
|
||||
per-core slots, estimated starts, last-task markers, equivalence classes, and
|
||||
cost summaries. Pipeline results also assign each core a stage. Materialization
|
||||
uses verified slots for execution order and merges only consecutive compatible
|
||||
instances. Graph/class lane identity does not imply core identity or execution
|
||||
order.
|
||||
|
||||
Dependencies and transfer costs share `getGraphBatchPublicationMap`.
|
||||
Statically proven physical-slot projections support many-to-many edges;
|
||||
unproven projections retain complete producer dependencies, including region
|
||||
captures. Malformed publication metadata fails graph construction.
|
||||
|
||||
Normative contracts:
|
||||
[graph fragments](../../.agents/invariants/GRAPH_COMPUTE_BATCH_INVARIANT.md),
|
||||
[pipeline stages](../../.agents/invariants/PIPELINE_SCHEDULING_INVARIANT.md),
|
||||
[target boundary](../../.agents/invariants/SPATIAL_TARGET_GENERALITY_INVARIANT.md),
|
||||
[synchronization](../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md),
|
||||
and [performance](../../.agents/invariants/PERFORMANCE_OPTIMIZATION_INVARIANT.md).
|
||||
|
||||
## Costs and interpretation
|
||||
|
||||
Execution and fixed transfer costs use integer nanoseconds, converted from
|
||||
target cycles. Bytes, elements, flits, weight slots, and lanes remain resource
|
||||
quantities. Memory work is rounded at its actual fragment/run granularity;
|
||||
runtime-free views cost zero. Transposes charge memory traffic and strided
|
||||
vector work; concatenation charges per-input blocks per outer row. Direct
|
||||
receives into assembly storage avoid duplicate endpoint-memory charges.
|
||||
Sub-byte storage is analyzable in Spatial but rejected by byte-addressed PIM
|
||||
communication lowering.
|
||||
|
||||
The evaluator separates serial work, per-core work, dependency critical path,
|
||||
summed transfer work, single-inference completion, and stage spans. Dependency
|
||||
paths exclude core-order constraints; completion includes them. Stage spans
|
||||
exclude cross-stage routing, restart/host synchronization, and contention.
|
||||
Simulator latency and measured throughput remain the performance gates.
|
||||
|
||||
Throughput scheduling uses one bounded joint optimizer. Initialization groups all
|
||||
lanes of an operation and computes one ordered partition with a prefix DP.
|
||||
The DP jointly assigns operation prefixes and at most sixteen units of spare
|
||||
core capacity. Each configured stage reserves one physical core. Quantization
|
||||
limits initialization only; refinement uses geometric core transfers, including one core.
|
||||
If the quality grid has no feasible state, a minimum-resource prefix DP checks
|
||||
every physical core count for each segment. This preserves feasibility over
|
||||
the segment assignments found by the constructive packers, independently of
|
||||
resource quantization. Packing failure remains a bounded-search limitation,
|
||||
not proved hardware infeasibility.
|
||||
For numeric depths greater than one, initialization requires exactly that many
|
||||
nonempty compute stages. Both prefix DPs enforce this requirement. Insufficient
|
||||
groups, resources, or legal stage cuts produce a diagnostic. A configured stage
|
||||
array does not establish active compute stages; realization verifies actual
|
||||
compute assignments and physical-core ownership. Packing priorities provide
|
||||
a starting point, not a timing guarantee.
|
||||
|
||||
Every proposed partition receives a minimax core budget for its changed stages.
|
||||
Unchanged stages retain their budgets. The allocator builds
|
||||
constructive ordered-packing curves and uses reuse-first resident-weight packing
|
||||
when order alone cannot realize a capacity bound. A feasible packing remains
|
||||
feasible with idle extra cores. All placements pass the existing topology-aware
|
||||
physical packing, operation-group, adjacency and capacity checks.
|
||||
Ordered packing returns an unavailable cost when no ordered assignment fits.
|
||||
Every finite feasibility cost has an ordered or reuse-first constructive assignment.
|
||||
Initialization retains that assignment before adding idle spare cores. If topology-aware
|
||||
greedy placement and reconstruction in physical task order fail, it uses the
|
||||
retained assignment.
|
||||
Task reordering cannot discard the initial partition's constructive capacity evidence.
|
||||
This evidence does not prove final backend legality.
|
||||
|
||||
Refinement retains the best evaluated schedule separately from expansion state.
|
||||
Its ordered neighborhood moves operation groups across adjacent stage boundaries.
|
||||
Only automatic depth search can insert or remove boundaries. Fixed-depth moves
|
||||
preserve every required compute stage. Refinement preserves contiguous groups
|
||||
in the initialization's topological order. Each changed block redistributes its
|
||||
core pool. A depth change recomputes the allocation for its complete partition.
|
||||
Core coordinates also transfer powers of two between stages, including one core.
|
||||
These moves cross packing plateaus within a bounded number of evaluations.
|
||||
Numeric pipeline depth and total physical resources remain fixed.
|
||||
Automatic search changes depth within the same physical resource budget.
|
||||
|
||||
Exact-depth feasible schedule sets are not nested. Discrete placement, packing,
|
||||
boundary transfers and restart synchronization can make the optimum output
|
||||
interval non-unimodal in depth. A bounded search adds optimization error at each
|
||||
depth. A poor initialized or refined schedule therefore cannot exclude nearby
|
||||
depths. Numeric-depth results and automatic-search results do not establish a
|
||||
global optimum over depths or placements.
|
||||
Complete-state queue intervals use integer elapsed times and generation counts,
|
||||
with a final floating-point division. Their precision is independent of the
|
||||
one-nanosecond MCR diagnostic bracket.
|
||||
|
||||
A cheap proxy ranks the neighborhood before physical packing and queue analysis.
|
||||
It uses ordered-packing curves, dependency spans and aggregate shared-memory demand.
|
||||
Refinement uses the target's existing per-operation execution costs, rather than
|
||||
redistributing aggregate processor work across operations.
|
||||
Processor service and critical recurrence contributions guide ties toward affected bottlenecks.
|
||||
The PIM adapter supplies target-neutral processor guidance from the shared periodic
|
||||
graph. PIM timing semantics remain outside Spatial.
|
||||
|
||||
The optimizer evaluates at most sixty-four complete Spatial queue costs and attempts
|
||||
at most 256 constructive allocations and physical packings.
|
||||
The shortlist contains at most 128 proposals. Initialization retains at most sixteen
|
||||
spare-core units. The packing-cost cache retains at most 256 ordered task lists.
|
||||
Each round evaluates at most two new placements.
|
||||
Each retained parent receives one queue-evaluation opportunity per round.
|
||||
The first round can evaluate two neighbors of its single parent.
|
||||
The expansion frontier contains the best unexhausted schedule and one best-first
|
||||
exploration schedule. Exploration uses waves of `ceil(sqrt(B))` expansions for
|
||||
queue budget `B`, then ages that schedule behind less-expanded schedules. This
|
||||
allows bounded lookahead through worse intermediate states while retaining the
|
||||
best incumbent. At budget 64, the wave has eight expansions.
|
||||
The two frontier slots do not change final selection.
|
||||
All evaluated schedules remain available for final comparison.
|
||||
Search stops at the evaluation or
|
||||
packing budget, or when all retained states have exhausted their legal neighborhood.
|
||||
Canonical stage/budget vectors, physical core order and evaluation index break
|
||||
ties deterministically. Actual physical placements, including inactive-core
|
||||
stage identities, are deduplicated. The final 2.1% near-equivalence policy compares
|
||||
the retained queue estimates. There are no independent legacy, sharing-aware,
|
||||
allocator-only or boundary-shift candidate-generation policies.
|
||||
|
||||
Unavailable timing, unsupported static forms or unproved recurrence explicitly
|
||||
stop a costed search. They are not silently discarded. One fixed-depth operation group or
|
||||
one distinct fixed-depth neighborhood schedule skips optional queue comparison and lowers
|
||||
once. Final backend resource retries remain restricted to already costed schedules.
|
||||
|
||||
`ComputeGraph` retains physical publication and consumer identities separately
|
||||
from aggregated dependency edges. Cross-stage demands charge one store per
|
||||
shared physical publication and one load per consumer transfer. Publication
|
||||
identity includes the immutable result generation, exact payload type, and
|
||||
physical source fragment. Scalar projections retain separate stores
|
||||
conservatively. Same-stage local/direct transfers incur no host traffic.
|
||||
Function inputs, constants, and outputs supply a separate baseline estimate.
|
||||
The target adapter supplies access width and read/write service times; request
|
||||
rounding precedes aggregation. Serialized service is shared by all stages and
|
||||
is not added to individual stage spans. Baseline loads remain approximate
|
||||
before placement, bufferization, aliasing, and load folding.
|
||||
Scalar publication stores round each contiguous source run separately.
|
||||
Consumer load counts can remain conservative before load folding.
|
||||
The scheduler evaluates boundary demand again after physical placement.
|
||||
Full graph fragments resolve to unique physical producers, so their sharing
|
||||
does not depend on reader placement. Deferred planning uses the same identity
|
||||
rule and retains separate loads, including repeated loads on one reader core.
|
||||
Placement ranks maximum per-core compute/incident-transfer demand, then stage
|
||||
completion and compute load; within 1% demand, stage span breaks the tie.
|
||||
These are placement heuristics, not a steady-state timing model.
|
||||
|
||||
## Periodic dependency diagnostics
|
||||
|
||||
`--pim-periodic-diagnostics` writes `reports/pipeline_periodic.json` after deferred
|
||||
boundary planning. This diagnostic does not change schedule selection or IR.
|
||||
It consumes the cached compute-instance costs, materialized core order, physical
|
||||
transfer families, publication store flags, and allocated READY/FREE registers.
|
||||
Compute runs remain atomic; their lanes and loop iterations are not expanded.
|
||||
Compact runs require one physical core; multi-core classes use per-lane steps.
|
||||
One event sequence represents each physical core. The model retains one planned
|
||||
load per physical consumer transfer and one store per shared publication.
|
||||
Later load folding or strided transfer splitting can change request granularity.
|
||||
|
||||
Edges express `t(v,k) >= t(u,k-d) + w`. Within-generation edges have distance
|
||||
zero. Each core's completion-to-entry edge has distance one. Reader-entry FREE
|
||||
signals therefore release the preceding generation through that edge. Signals
|
||||
join their exact planned WAIT count. Dissemination barriers, restart permissions,
|
||||
and the downstream release tree retain their core identities and order.
|
||||
The diagnostic checks its event-register summary against the emitted program
|
||||
in the synchronization tests; it does not replace deadlock verification.
|
||||
|
||||
The injected target describes direct-transfer completion and link, local-memory,
|
||||
shared-memory, and signal timing. The current adapter specifies peer permission
|
||||
before a source read. SEND completion follows the read and payload enqueue;
|
||||
RECV completion also requires payload delivery and a destination write.
|
||||
Unsupported or incomplete target timing produces an `unavailable` report.
|
||||
|
||||
The analysis brackets the maximum cycle ratio within one nanosecond. It tests
|
||||
edge delays `w - II*d`, sweeping the distance-zero DAG between recurrence
|
||||
relaxations. A positive predecessor cycle can terminate an infeasible probe early.
|
||||
The final witness pass retains the full relaxation procedure and deterministic
|
||||
witness selection. Contiguous adjacency offsets preserve the original edge order.
|
||||
Probes reuse one flattened DAG edge order. Recurrence arithmetic and witness
|
||||
tie-breaking remain unchanged. At most `R+1` sweeps detect a positive cycle,
|
||||
where `R` counts positive-distance edges. Bisection uses at most 64 tests. Timing outside the
|
||||
supported numeric range produces an explicit unavailable result. A predecessor
|
||||
cycle supplies a witness, including delay, iteration distance, cores, and links.
|
||||
Detailed witness output is limited to 128 edges; totals cover the entire cycle.
|
||||
|
||||
The reported interval estimate is the maximum of the modeled recurrence,
|
||||
per-core compute work, and aggregate serialized shared-memory service. Memory
|
||||
service is never assigned a fixed global request order. Taking the maximum
|
||||
does not add the same service twice. The within-generation dependency span is
|
||||
reported separately and is not an initiation interval.
|
||||
|
||||
These are conditional estimates for the abstract execution model, not exact
|
||||
simulator predictions or guaranteed physical lower bounds. Serial compute costs
|
||||
can overestimate overlapping work. Baseline memory accesses retain their
|
||||
aggregate service bound, but their positions are not modeled. Communication
|
||||
introduced after deferred realization, including final output collection, is
|
||||
also absent. Instruction issue, local contention, network injection queues, and
|
||||
memory arbitration remain unmodeled. Missing effects are listed in the report;
|
||||
`selection_eligible` remains false. This plan-level diagnostic does not rank
|
||||
production candidates. Production extracts execution events from realized Spatial
|
||||
and evaluates them with the shared queue engine.
|
||||
|
||||
For `V` events, `E` edges, and `R` recurrence edges, construction requires
|
||||
`O(T + F + S log S)` time and `O(V + E + S)` storage, for existing compute
|
||||
instances `T`, physical transfers `F`, and synchronization events `S`.
|
||||
Analysis requires `O(L (R+1) (V+E))` time and `O(V+E)` storage, where `L <= 64`.
|
||||
Here `R` is at most the number of active physical cores. There is no dense
|
||||
all-core dependency matrix or inference-generation unrolling.
|
||||
For `C` analyzed candidates, time scales by `C`; scratch storage can be reused.
|
||||
The current diagnostic analyzes only the selected schedule (`C = 1`).
|
||||
|
||||
### Post-codegen instruction diagnostic
|
||||
|
||||
`raptor-periodic` provides an explicit, read-only diagnostic over an emitted
|
||||
binary artifact. It accepts native or oracle-exported artifacts. Use the
|
||||
oracle-exported artifact when comparing against Pimsim performance results:
|
||||
|
||||
```bash
|
||||
build_release/Release/bin/raptor-periodic /tmp/model/pimsim_nn \
|
||||
--pim-target-config=validation/pimsim_configs/pimcomp/arch-a/throughput_config_1000ms.json \
|
||||
--core-count=168 --crossbar-count=96 --crossbar-size=128 > /tmp/periodic.json
|
||||
```
|
||||
|
||||
The diagnostic uses physical instruction files and their array-group map.
|
||||
Each file owns one physical core's work, including all lanes and static loop
|
||||
iterations already emitted there. It does not expand compiler loops or batches.
|
||||
It replaces Spatial compute costs rather than adding instruction costs to them.
|
||||
The lightweight compiler report remains separate and does not invoke this tool.
|
||||
|
||||
The supported execution contract requires ROB capacity one. Non-scalar
|
||||
instructions therefore retain their serial execution order. Local compute and
|
||||
blocking memory runs become weighted chunks between communication events.
|
||||
Every emitted global request contributes its actual size, rounding, and count.
|
||||
Inputs, constants, split transfers, folded loads, and output collection are
|
||||
included through their emitted instructions. Their positions relative to
|
||||
communication remain explicit. The global service bound remains separate;
|
||||
the model does not impose an order on different cores' global requests.
|
||||
|
||||
Timing queries reuse the injected memory, link, and matrix definitions.
|
||||
PIM instruction semantics belong to the compiler target adapter. Vector
|
||||
writeback follows the oracle's actual width rules. Matrix writeback uses the
|
||||
physical array-group width. Local-memory timing uses its own configured period.
|
||||
The oracle passes `vector_latency_cycle` directly to a nanosecond wait.
|
||||
This parameter does not scale with the processor period; no separate vector
|
||||
clock exists in the supported oracle configuration.
|
||||
In the current oracle, global loads return zero network payload bytes.
|
||||
Global stores retain their outgoing payload cost.
|
||||
|
||||
The source switch has one unbounded FIFO for outgoing requests. Enqueue does
|
||||
not wait for earlier requests. FIFO dispatch waits for their completion.
|
||||
Direct SEND requires permission delivery before the source read. Its payload
|
||||
enqueue event coincides with source-read completion. SEND completes after
|
||||
enqueue, independently of FIFO dispatch or payload delivery. RECV requires delivery and
|
||||
destination write. Permission responses join both peer readiness and the
|
||||
receiver's outgoing FIFO. SYNC delivery can precede its local completion.
|
||||
The model retains WAIT counts, restart events, and cross-generation FIFO state.
|
||||
It does not replace the compiler's synchronization or deadlock verification.
|
||||
|
||||
`--model-network-queues=false` and `--model-issue=false` support timing
|
||||
comparisons. The latter omits scalar issue and retirement delays while retaining
|
||||
SYNC's instruction-defined execution time. Completion notifications can join
|
||||
the current edge before the clock process runs. The model uses minimum
|
||||
retirement delays; it does not reproduce SystemC clock-phase ordering.
|
||||
Scalar issue is charged serially, so these estimates are not guaranteed
|
||||
physical lower bounds. The base recurrence estimate omits global arbitration,
|
||||
frontend buffering, and initial bootstrap. Production does not rank candidates
|
||||
with this recurrence-only estimate.
|
||||
Reports with at most 128 events include `timing_graph` for focused timing checks.
|
||||
Its dependencies distinguish payload enqueue from FIFO dispatch and delivery.
|
||||
The instruction test accepts `--pimsim /path/to/ChipTest` for optional fast-mode
|
||||
timing comparisons. These cover both hardware profiles and distinct processor,
|
||||
local-memory, and vector latency settings.
|
||||
|
||||
For `N` emitted instructions, `F` direct transfers, `S` synchronization events,
|
||||
and `P` active cores, construction takes `O(N + (F+S) log(F+S))` time.
|
||||
The indexed graph uses `O(F+S+P)` space and at most `2P` recurrence edges.
|
||||
Global requests are counted during the same scan without per-request graph
|
||||
nodes. One instruction file is memory-mapped at a time. Maximum-cycle-ratio
|
||||
analysis uses the same bounded algorithm as the lightweight diagnostic.
|
||||
|
||||
`--model-memory-controller` adds a separate `memory_controller` estimate.
|
||||
Each global request retains its readiness, transport, service, and completion
|
||||
dependencies. The controller serves requests in predicted arrival order.
|
||||
Read and write requests share that FIFO. Zero-size requests also join it.
|
||||
Source switches remain occupied until transport completion. The model does not
|
||||
assign a fixed global request order or consume simulator trace order.
|
||||
|
||||
The analysis executes the indexed periodic graph with timestamped tokens.
|
||||
FIFO tokens retain dependencies across generations; the graph is not copied.
|
||||
A request arrival reserves the controller after earlier arrivals, and its
|
||||
completion enables dependent events. Independent cores and switches remain
|
||||
concurrent. The maximum-cycle-ratio solver and its report remain unchanged.
|
||||
|
||||
The queue estimate compares adjacent two-generation windows with the oracle's
|
||||
one-percent convergence threshold. It reports the mean interval across both
|
||||
windows. Per-core queue waits use the corresponding four completed body
|
||||
generations. The maximum request wait includes bootstrap. Event-index order
|
||||
resolves simultaneous readiness. A second run reverses that order and reports
|
||||
`alternative_tie_interval_ns`. These two orders are sensitivity checks, not
|
||||
bounds over every possible tie order. Clock phases and frontend overlap remain
|
||||
approximate. The standalone report remains read-only.
|
||||
Production evaluates Spatial-derived events with the shared queue engine.
|
||||
|
||||
For `R` global requests, the queue mode adds `O(R)` events and dependencies.
|
||||
For `V` resulting events, `E` dependencies, and generation bound `K`, execution
|
||||
takes `O(K(E + V log V))` time. Storage is `O(V + E + B)`, where `B` counts
|
||||
pending tokens. The event heap contains at most one event per node. FIFO token
|
||||
storage retains pending generations, rather than instruction-stream copies.
|
||||
The diagnostic limits each event to 64 generations and processed events to
|
||||
`16(V + E)`. It reports `unavailable` if either bound prevents convergence.
|
||||
The two tie-order runs reuse the same graph. Production uses queue execution for costs and maximum-cycle-ratio analysis for bounded search guidance.
|
||||
The standalone frontend retains the recurrence witness. Neither analysis changes latency PEFT.
|
||||
|
||||
## Default throughput selection
|
||||
|
||||
Full PIM code generation uses Spatial-only queue-aware selection for `--pipeline > 1` and `--pipeline=auto`.
|
||||
Latency PEFT and `--pim-only-codegen` retain their existing behavior.
|
||||
Intermediate emission retains the initialized schedule and stops at its requested stage.
|
||||
Its schedule can differ from the final program. Automatic depth requires full
|
||||
code generation and is rejected for intermediate emission.
|
||||
|
||||
The compiler performs these steps:
|
||||
|
||||
1. Run the frontend, layout planning, and graph preparation once.
|
||||
2. Construct one legal initial partition, allocate cores, and place its work.
|
||||
3. Rank legal joint partition/allocation moves with inexpensive resource proxies.
|
||||
4. Realize each admitted schedule in an independent clone of the prepared checkpoint.
|
||||
5. Query the target adapter over realized Spatial IR, then release the clone.
|
||||
6. Require supported static forms, available costs, and proved modeled recurrence.
|
||||
7. Refine the incumbent and exploration frontier within sixty-four total queue evaluations.
|
||||
8. Apply the existing 2.1% near-equivalence rule to the evaluated schedules.
|
||||
9. Realize the selected schedule again from the unchanged checkpoint.
|
||||
10. Lower, allocate, verify, and emit only the selected program.
|
||||
|
||||
A single fixed-depth candidate skips event extraction, queue analysis, recurrence proof, and comparison.
|
||||
It is realized and lowered once, even when optional timing is unavailable.
|
||||
Auto still validates its p1 queue cost when no pipeline candidate can be initialized.
|
||||
No rejected candidate enters PIM IR or instruction generation during cost evaluation.
|
||||
Constants and weights remain shared immutable attributes in the MLIR context.
|
||||
Candidate operations, communication plans, and synchronization state remain independent.
|
||||
No full candidate compilation directories are created.
|
||||
|
||||
`SchedulingTarget::estimateRealizedScheduleCost` is the read-only whole-schedule query.
|
||||
Its typed result carries both intervals, recurrence evidence, static lowering support,
|
||||
failure reasons, and the selection margin. Unknown support remains explicit.
|
||||
The target supplies model evidence. Spatial applies the 2.1% selection policy margin.
|
||||
Selection does not read JSON diagnostics. Reports serialize the typed results.
|
||||
Spatial owns candidate generation, legality, placement, and target-neutral comparison.
|
||||
The PIM adapter owns execution-event extraction, instruction timing, and resource contention.
|
||||
Pimsim-nn omits `vsoftmax` before fetch, so the PIM queue model assigns it no timed work.
|
||||
Input materialization, surrounding instructions, transfers, and synchronization retain their costs.
|
||||
Functional simulation still executes Softmax. Estimated timing and energy exclude Softmax work.
|
||||
The shared queue engine models controller arrival arbitration and cross-generation dependencies.
|
||||
The compiler does not execute candidate programs or invoke a simulator.
|
||||
|
||||
Spatial extraction permits at most one million operation visits per physical core.
|
||||
The total visit count is diagnostic; adding cores does not reduce another core's analysis allowance.
|
||||
Abstract queue construction permits two million non-work event visits per candidate.
|
||||
The complete-state recurrence limits remain unchanged.
|
||||
|
||||
Both arbitration policies must establish complete-state recurrence within bounded analysis budgets.
|
||||
Their estimates are sensitivity checks, not formal bounds.
|
||||
The candidate with the lowest larger estimate must separate from the initialized schedule.
|
||||
Comparison uses `[min(ties)/1.021, max(ties)/0.979]`.
|
||||
Close alternatives retain the initialized schedule. The 2.1% margin is a policy heuristic.
|
||||
Spatial timing predictions have no formal accuracy bound.
|
||||
The search finds the best distinguishable candidate in its bounded set, without global optimality.
|
||||
|
||||
Unavailable timing, unknown static support, or unproved recurrence stops a multi-candidate comparison.
|
||||
The diagnostic identifies each affected candidate and property.
|
||||
The compiler does not silently exclude unknown candidates or use instruction-level fallback selection.
|
||||
|
||||
Static preflight does not prove final backend legality.
|
||||
The selected candidate runs through normal bufferization, allocation, and backend verification.
|
||||
A backend owner can mark a resource-limit diagnostic as candidate-specific.
|
||||
Currently, the local-memory allocator marks signed 32-bit address-space exhaustion.
|
||||
The compiler discards that failed clone, explicitly records its rejection, and selects again from the remaining estimated schedules.
|
||||
The first remaining schedule becomes the reference for the same selection policy.
|
||||
Each schedule is attempted at most once. No graph or placement constraints are relaxed.
|
||||
Unclassified or systemic backend failures stop compilation immediately.
|
||||
Code-generation failures also stop compilation when recovery cannot be justified.
|
||||
If every candidate fails, one diagnostic lists all attempted candidates and causes.
|
||||
|
||||
`reports/pipeline_selection.json` records Spatial costs, eligibility, selection, and backend attempts.
|
||||
It also records search parents, compact task-stage runs, core budgets, recurrence contributions, termination, attempts, queue budget, and phase times.
|
||||
Phase times separate neighborhood scoring, constructive packing, dependency-witness
|
||||
analysis, and queue execution with its complete-state proof.
|
||||
`--enable-timing` adds per-pass lowering times and IR operation/value counts.
|
||||
Final instruction generation uses the normal compiler timing report.
|
||||
Explicit Spatial exports and IR dumps reconstruct pre-lowering artifacts for the selected schedule.
|
||||
They do not change the emitted program. Diagnostic MLIR dumps elide large constants and are not lossless checkpoints.
|
||||
|
||||
### Fixed and automatic depth
|
||||
|
||||
`--pipeline=1` retains latency PEFT, including its existing instruction program.
|
||||
`--pipeline=N`, for N greater than one, requires exactly N nonempty compute stages.
|
||||
Every stage has physical cores. Boundary refinement cannot remove a required stage.
|
||||
The compiler rejects infeasible exact depths instead of compacting stages.
|
||||
|
||||
`--pipeline=auto` compares steady-state output intervals with the same queue model
|
||||
and final selection policy. Its p1 candidate uses the original PEFT schedule.
|
||||
Auto adds the existing stage-zero restart barrier to the PEFT placement. This
|
||||
protects changing input generations without changing numeric p1 latency compilation.
|
||||
The queue model repeats that synchronized program; its cost is not single-inference latency.
|
||||
If PEFT initialization fails, the report records that construction failure and
|
||||
starts from a constructively feasible pipeline schedule. This is not proof that
|
||||
all possible p1 placements are infeasible.
|
||||
|
||||
The legal ordered-prefix graph bounds the maximum depth, together with the
|
||||
physical-core count. Auto shares segment packing curves and graph constraints
|
||||
across depth initializations. Each depth retains its resource grid and
|
||||
deterministic DP tie order. Reserved-core counts change those grids, so their
|
||||
DP states cannot be reused unchanged across depths. Minimum-resource completion
|
||||
reuses the shared integer-core cost curves.
|
||||
|
||||
Auto initialization covers depth 2 and the maximum depth, then bisects the
|
||||
largest remaining depth gap. Ties prefer the shallower gap. At most
|
||||
`min(1+ceil(log2(D-1)), D-1, floor(B/2))` pipeline seeds are constructed for
|
||||
maximum depth D and queue budget B. Failed depth initializations are reported;
|
||||
they do not invalidate feasible depths. All seeds and refinements share
|
||||
sixty-four complete queue evaluations and the same incumbent/frontier policy.
|
||||
Untested depths and unexplored neighbors remain explicit search limitations.
|
||||
This bounded search does not prove a global optimum.
|
||||
An unavailable cost or unproved recurrence for an admitted schedule stops comparison.
|
||||
Only the final selected program enters PIM lowering.
|
||||
|
||||
`pipeline_selection.json` records requested and selected depths, explored depths,
|
||||
per-depth initialization status, active stage identities, queue costs, search parents,
|
||||
expansion counts, budgets, and the termination reason.
|
||||
|
||||
### Static analysis, diagnostics, and external validation
|
||||
|
||||
Production decisions use the input graph, compiler options, physical plans, and configured target parameters only.
|
||||
Identical static inputs produce the same decision regardless of historical measurements.
|
||||
There are no measured-latency caches, workload lookup tables, or fitted timing corrections.
|
||||
|
||||
`raptor-periodic` retains the instruction-derived analyzer as a standalone validation frontend.
|
||||
It shares the same timing definitions and queue engine with Spatial event evaluation.
|
||||
Optional diagnostics expose resource work, recurrence, and ordered-request fingerprints.
|
||||
Offline Pimsim fast-mode runs validate predictions and emitted programs.
|
||||
Simulator measurements never enter production selection.
|
||||
|
||||
For `C <= 64` candidates, scheduling metadata uses `O(C(T+P))` storage for `T` compute instances and `P` cores.
|
||||
Placement identities require `O(C(T+P))` storage; ordered-set deduplication compares
|
||||
identities in `O((T+P) log C)` time per insertion. The active frontier has at most two schedules.
|
||||
Auto adds `O(G²)` time and `O(G)` space for its legal depth upper bound.
|
||||
For G operation groups, S numeric stages, P cores, and U spare-core units
|
||||
(at most sixteen), the numeric quality DP has `O(S G² U²)` transitions and
|
||||
`O(G² U + S G U)` storage. Minimum-resource completion can require `O(G² P)`
|
||||
packing queries and `O(S G²)` transitions.
|
||||
|
||||
Auto shares segment curves across its depth initializations. Ordered minimax
|
||||
queries reuse threshold scans and monotone neighboring-core bounds. Curves query only the
|
||||
union of core counts used by the selected depth grids. Feasibility completion
|
||||
computes missing integer-core costs lazily, with the same constructive packer.
|
||||
Constructive unordered packing remains necessary when ordered packing fails. Illegal stage segments
|
||||
have no packing queries. For maximum depth D, all depth-specific resource grids
|
||||
have `O(L D G² U²)` DP transitions in total for L initialized depths.
|
||||
Segment costs require at most `O(G² P Kpack)` constructive query work, with
|
||||
reused ordered-threshold scans reducing repeated scalar searches.
|
||||
Peak storage is `O(G² P + D G U + L T)` for T compute instances, plus packing
|
||||
scratch. Uninitialized depths do not allocate DP states.
|
||||
Each initialized depth retains a compact assignment and its constructive core
|
||||
counts. The shared table is released before queue evaluation.
|
||||
Depth seed reconstruction does not rerun packing-cost construction or the DP.
|
||||
Profiles report segment work, DP transitions, threshold scans, and physical
|
||||
initialization separately.
|
||||
A round streams legal boundary and core moves into a shortlist of at most `2C`.
|
||||
Each parent builds stage resource and dependency summaries in `O(T+E+P)` time and storage.
|
||||
Exact packing costs and resource lower bounds share a search-local cache of at most
|
||||
256 ordered task lists, independent of the queue budget. The immutable task costs,
|
||||
weights and target fix each query. LRU eviction changes recomputation only.
|
||||
For maximum list length T, the cache uses `O(256(T+P))` storage and
|
||||
`O(T log 256)` lookup time; eviction scans at most 256 entries.
|
||||
Each parent proposes `O(G + S² log P)` group, cut, and core moves.
|
||||
For `M` proposed assignments, cheap allocation and scoring cost
|
||||
`O(M (T log T + S P + E + F + S Kpack))`, plus bounded shortlist comparisons,
|
||||
where `Kpack` is one existing ordered-packing query's cost.
|
||||
Constructive allocation builds at most `S P` ordered-packing queries per admitted
|
||||
partition. The graph and weight indices are reused. Search performs at most
|
||||
256 physical packings; queue costs remain capped at sixty-four.
|
||||
Recurrence guidance uses the shared bounded maximum-cycle-ratio solver.
|
||||
Candidate realization and extraction are sequential; complete candidate modules are not retained.
|
||||
Normal successful compilation performs one candidate-specific backend lowering.
|
||||
Recovery performs at most `C` lowerings. Retry selection costs `O(C²)` time and `O(C)` metadata.
|
||||
The bounded queue-analysis costs are described in the implementation notes.
|
||||
|
||||
## Capacity and recovery
|
||||
|
||||
Distinct-weight union / per-core capacity is a lower bound; an oversized task
|
||||
is infeasible. Ordered pack counts estimate budgets, and failed heuristic
|
||||
packing does not prove infeasibility. Exhausted budgets restart from lower
|
||||
bounds and constructive packing establishes feasibility.
|
||||
|
||||
Latency reservations try load/communication-aware placement, then
|
||||
largest-weight-first and shared reuse-first best fit on failure. Pipeline
|
||||
packing compares arrival/load-aware candidates and uses constructive recovery.
|
||||
The shared constructor retries in reverse order, then at most 16 single-choice
|
||||
deviations within 65,536 core-candidate checks. Successful placements are
|
||||
preserved. Exhausted search produces a bounded diagnostic, not a claim of
|
||||
proved hardware infeasibility.
|
||||
|
||||
## Complexity and limits
|
||||
|
||||
Let `T` be tasks, `E` dependencies, `P` cores, `G` groups, `S` stages,
|
||||
`R` weight references, `W` distinct weights, `C` modeled work, `F` physical
|
||||
fragment/consumer demands, and resource quantization `Q <= 16`.
|
||||
|
||||
| Analysis | Time / storage |
|
||||
|---|---|
|
||||
| Schedule evaluation | `O((T + E) log T + P)` / `O(T + E + P)` |
|
||||
| Weight indexing | Up to `O(R W)` equality comparisons |
|
||||
| Weight lower bounds | `O(R + W)` / `O(W)` bits |
|
||||
| Constructive best fit | `O(T log T + P R + P W)` / `O(P W)` bits plus `O(T + P)`; bounded retries only on failure |
|
||||
| Joint initialization DP | `O(G² Q Kpack + S G² Q²)` time / `O(G² Q + S G Q)` storage; `Kpack` is one constructive pack-cost query |
|
||||
| Feasibility completion, only if the quality grid fails | `O(G² P Kpack + S G²)` time / `O(G² + S G)` additional storage |
|
||||
| Neighborhood memory service | Expected `O(T + F)` per partition / `O(T + F)` scratch |
|
||||
| Topology clustering / cached PEFT distances | `O(P²)` time |
|
||||
| Concat cost extraction | `O(A D)` for `A` inputs of rank `D`; constant auxiliary space |
|
||||
| Cached pipeline priorities | `O(T + D)` time / `O(T + G)` space for `D` template-body operations |
|
||||
| Exact projections | `O(Q + L)` time for `Q` slot visits and `L` producer lanes; repeated demands aggregate by projection and fragment |
|
||||
| Conservative producer tracing | Linear in the input projection DAG, including captures |
|
||||
|
||||
Latency insertion-gap searches can remain quadratic. Issue overhead,
|
||||
eliminated assembly copies, contention, and pipeline synchronization remain
|
||||
cost approximations. Changes require matched execution measurements.
|
||||
Loop-invariant projections use trip-count multiplication. Loop-invariant
|
||||
resident weights are collected once. Loop-dependent projections and weights
|
||||
can still require iteration visits; retained projection demands scale with
|
||||
distinct physical fragments instead of repeated visits.
|
||||
@@ -1,63 +0,0 @@
|
||||
# Spatial layout capabilities
|
||||
|
||||
This reference describes the alternatives advertised by
|
||||
[`SpatialLayoutCapabilities.cpp`](../../src/PIM/Conversion/ONNXToSpatial/Passes/Analyses/SpatialLayoutCapabilities.cpp),
|
||||
through `SpatialLayoutCapabilityInterface`. Each alternative specifies all
|
||||
operand layouts and one result layout; it is not a global promise that every
|
||||
shape or target can use that layout.
|
||||
|
||||
## Physical layouts
|
||||
|
||||
Logical tensor coordinates remain NCHW. The physical enum is defined in
|
||||
[`Spatial.td`](../../src/PIM/Dialect/Spatial/Spatial.td).
|
||||
|
||||
| Layout | Contract and current use |
|
||||
|---|---|
|
||||
| `DenseNCHW` | Ordinary dense storage; first/default alternative for every layout-aware plan. |
|
||||
| `NHWCRowStrip` | Physical row strips of channel vectors for logically NCHW tensors; compatible operations can preserve this representation through a chain. |
|
||||
| `Fragmented` | Existing fragmented input accepted by Flatten for dense reconstruction; no current capability advertises it as a result alternative. |
|
||||
| `NCHWRowStrip` | Reserved NCHW-oriented row-strip enum; no current capability advertises it as an alternative. |
|
||||
|
||||
## Compatibility matrix
|
||||
|
||||
Every operation below also advertises all-dense operands → `DenseNCHW`.
|
||||
Here `R` means `NHWCRowStrip`, `D` means `DenseNCHW`; Conv's other operands
|
||||
retain the layouts supplied to its interface on the `R` path.
|
||||
|
||||
| Plan operation | Additional operand → result alternatives | Interface gate |
|
||||
|---|---|---|
|
||||
| Conv2D | Dense input → R; R input → R | `canLowerConvPlanToRowStrip`; `canConsumeAndProduceRowStrip`, respectively. |
|
||||
| Flatten | Fragmented → D; R → D | Fragmented input already present; `canLowerFlattenFromRowStrip` for R. |
|
||||
| Relu | R → R | Input already R. |
|
||||
| SiLU | R → R | Input already R; intrinsic cost −3 instead of the generic R cost −2. |
|
||||
| ResizeNearest | R → R | Input already R and `canLowerResizeNearestPlanToRowStrip`. |
|
||||
| MaxPool2D | D → R; R → R | `canLowerMaxPoolPlanToRowStrip`. |
|
||||
| GlobalAveragePool | D → R; R → R | `canLowerGlobalAveragePoolPlanToRowStrip`. |
|
||||
| BiasAdd | (R data, D bias) → R | Ranked result, R data input, and `isSupportedBiasAddValue` for the bias shape. |
|
||||
| Add | (R, R) → R | Both data operands already R. |
|
||||
| Concat | All R inputs → R | Nonempty operand list, all already R. |
|
||||
|
||||
The named predicates live in the [plan-lowering implementation](../../src/PIM/Conversion/ONNXToSpatial/Passes/Transforms)
|
||||
and [bias helper](../../src/PIM/Conversion/ONNXToSpatial/Common/BiasAddUtils.hpp). They check operation geometry and
|
||||
target resources; the matrix does not replace those legality checks.
|
||||
|
||||
## Selection and materialization
|
||||
|
||||
[`SpatialLayoutPlanningPass.cpp`](../../src/PIM/Conversion/ONNXToSpatial/Passes/Transforms/SpatialLayoutPlanningPass.cpp)
|
||||
starts every plan at its dense alternative. It scores intrinsic cost, operand
|
||||
layout mismatches, and downstream inability to accept the candidate layout.
|
||||
Strictly cheaper alternatives replace the current selection; ties preserve it.
|
||||
Traversal alternates forward/reverse order for at most `2 × plan_count + 1`
|
||||
rounds. Nonconvergence fails the pass with a diagnostic.
|
||||
|
||||
Results returned from the function must remain dense. The pass records selected
|
||||
layouts and inserts explicit `spat.materialize_layout` operations where selected
|
||||
producer/consumer contracts disagree, including non-layout-aware consumers of
|
||||
non-dense values. It verifies exact operand/result compatibility before
|
||||
[`LowerSpatialPlans`](../../src/PIM/Conversion/ONNXToSpatial/Passes/Transforms/LowerSpatialPlansPass.cpp) lowers plans
|
||||
and materializations.
|
||||
|
||||
`--pim-disable-spatial-planning` skips cost selection, choosing alternative 0
|
||||
for every plan. The planning/materialization/verification pass still runs.
|
||||
ONNX rewrites and later graph merging are unchanged; disabling layout planning
|
||||
does not request fusion or removal of separate elementwise graph nodes.
|
||||
@@ -1,108 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check operation coverage, required content, and local reference links (stdlib only)."""
|
||||
|
||||
from collections import Counter
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REFERENCE = ROOT / "docs/dialects/index.html"
|
||||
FIELDS = {"syntax", "inputs", "outputs", "attributes", "semantics", "constraints"}
|
||||
|
||||
|
||||
class ReferenceParser(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.ids = []
|
||||
self.links = []
|
||||
self.articles = []
|
||||
self.current = None
|
||||
self.field = None
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
attrs = dict(attrs)
|
||||
if "id" in attrs:
|
||||
self.ids.append(attrs["id"])
|
||||
if tag == "a" and "href" in attrs:
|
||||
self.links.append(attrs["href"])
|
||||
if tag == "article":
|
||||
self.current = (attrs.get("id", ""), {})
|
||||
self.articles.append(self.current)
|
||||
if self.current is not None and "data-field" in attrs:
|
||||
self.field = attrs["data-field"]
|
||||
self.current[1][self.field] = ""
|
||||
|
||||
def handle_data(self, data):
|
||||
if self.current is not None and self.field:
|
||||
self.current[1][self.field] += data
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag in {"pre", "dd"}:
|
||||
self.field = None
|
||||
if tag == "article":
|
||||
self.current = None
|
||||
|
||||
|
||||
def operation_names(sources):
|
||||
"""Follow named operation base classes, including shared compute/plan bases."""
|
||||
sources = [re.sub(r"/\*.*?\*/|//[^\n]*", "", source, flags=re.S) for source in sources]
|
||||
classes = {"SpatOp": "spat", "PimOp": "pim"}
|
||||
bases = re.findall(r"\bclass\s+(\w+)[^{;]*?:\s*(\w+)\s*<", "\n".join(sources))
|
||||
for _ in range(len(bases)):
|
||||
for name, base in bases:
|
||||
if base in classes:
|
||||
classes[name] = classes[base]
|
||||
return {
|
||||
classes[base] + "." + mnemonic
|
||||
for source in sources
|
||||
for base, mnemonic in re.findall(r'\bdef\s+\w+\s*:\s*(\w+)<\s*"([^"]+)"', source)
|
||||
if base in classes
|
||||
}
|
||||
|
||||
|
||||
def check(document):
|
||||
parser = ReferenceParser()
|
||||
parser.feed(document)
|
||||
expected = operation_names(
|
||||
definition.read_text() for definition in sorted((ROOT / "src/PIM/Dialect").rglob("*.td"))
|
||||
)
|
||||
errors = []
|
||||
if not expected:
|
||||
errors.append("No operation definitions found; check the ODS discovery pattern")
|
||||
actual = {name for name, _ in parser.articles}
|
||||
for name in sorted(expected - actual):
|
||||
errors.append(f"Missing operation: {name}")
|
||||
for name in sorted(actual - expected):
|
||||
errors.append(f"Unknown/stale operation: {name}")
|
||||
for name, count in Counter(parser.ids).items():
|
||||
if count > 1:
|
||||
errors.append(f"Duplicate HTML id: {name}")
|
||||
for name, fields in parser.articles:
|
||||
for field in sorted(FIELDS):
|
||||
if not fields.get(field, "").strip():
|
||||
errors.append(f"{name}: missing/empty {field}")
|
||||
if name not in fields.get("syntax", ""):
|
||||
errors.append(f"{name}: syntax does not contain the exact operation name")
|
||||
if "#" + name not in parser.links:
|
||||
errors.append(f"{name}: missing index/permalink")
|
||||
for href in parser.links:
|
||||
link = urlsplit(href)
|
||||
if link.scheme or link.netloc:
|
||||
continue
|
||||
if not link.path:
|
||||
if unquote(link.fragment) not in parser.ids:
|
||||
errors.append(f"Broken fragment: {href}")
|
||||
elif not (REFERENCE.parent / unquote(link.path)).is_file():
|
||||
errors.append(f"Broken local link: {href}")
|
||||
return errors
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
failures = check(REFERENCE.read_text())
|
||||
if failures:
|
||||
print("\n".join(failures), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print("Dialect reference: operation coverage, content fields, and local links OK")
|
||||
@@ -1,142 +0,0 @@
|
||||
"""Generate the repeating manuscript border: .venv/bin/python docs/dialects/generate_border.py."""
|
||||
|
||||
from math import atan2, cos, degrees, pi, sin
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
OUTPUT = Path(__file__).with_name("jurassic-border.svg")
|
||||
GOLD = "#c6a45f"
|
||||
|
||||
|
||||
def generate():
|
||||
parts = ['''<svg xmlns="http://www.w3.org/2000/svg" width="180" height="960" viewBox="0 0 180 960">
|
||||
<title>Illuminated manuscript foliage border</title>
|
||||
<desc>Procedural gold scrollwork, acanthus leaves, raptor medallions, rosettes, and pearl ornament on deep green.</desc>
|
||||
<defs>
|
||||
<linearGradient id="gold" x2="1" y2=".4">
|
||||
<stop stop-color="#80602e"/><stop offset=".35" stop-color="#ead19a"/>
|
||||
<stop offset=".6" stop-color="#b38a46"/><stop offset="1" stop-color="#e2bf73"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="jade" x2="1" y2="1">
|
||||
<stop stop-color="#749281"/><stop offset=".45" stop-color="#365d50"/><stop offset="1" stop-color="#152d27"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="red" x2="1" y2="1">
|
||||
<stop stop-color="#b86e60"/><stop offset=".5" stop-color="#793c39"/><stop offset="1" stop-color="#3e2527"/>
|
||||
</linearGradient>
|
||||
<g id="leaf" stroke="#c6a45f" stroke-width=".65" stroke-linejoin="round">
|
||||
<path fill="url(#jade)" d="M0 0C-3-8-16-7-16-19Q-11-15-8-18C-17-24-14-34-12-38Q-8-29-4-31C-10-40-3-49 1-54C0-41 11-37 7-29Q14-32 15-39C23-26 15-21 10-18Q16-17 20-22C22-9 9-10 0 0Z"/>
|
||||
<path d="M0-2Q-4-23 1-48M-2-12Q-11-14-13-20M-3-24Q-9-25-11-32M-2-34 0-41M-2-10Q11-11 16-17M-3-21Q9-22 13-31" fill="none"/>
|
||||
<path d="M-5-13Q-9-17-9-19M1-27Q4-31 3-35" fill="none" stroke="#e6d2a0" stroke-width=".45"/>
|
||||
</g>
|
||||
<g id="bud" stroke="#c6a45f" stroke-width=".65">
|
||||
<path d="M0 0Q-14-10-7-23Q-2-22 0-17Q2-22 7-23Q14-10 0 0Z" fill="url(#red)"/>
|
||||
<path d="M0 0Q-5-13 0-27Q5-13 0 0Z" fill="url(#gold)"/>
|
||||
<path d="M-6-6 0 0 6-6" fill="none"/>
|
||||
</g>
|
||||
<g id="raptor" stroke="#c6a45f" stroke-linejoin="round">
|
||||
<circle r="46" fill="#090f0c" stroke-width="1.5"/>
|
||||
<circle r="42" fill="#14221c" stroke-width=".5"/>
|
||||
<circle r="39" fill="none" stroke-width=".5" stroke-dasharray="1 3"/>
|
||||
<path d="M-26 29Q-15 12-24-1L-32-5-25-9-32-15-22-16-27-24-15-21-16-30-5-23Q7-26 17-15L34-9Q39-6 34 0L14 4 31 9Q33 13 26 16L6 12Q-2 17 0 31Z" fill="url(#jade)" stroke-width="1.2"/>
|
||||
<path d="M-26 29Q-3 25-5 6Q-16-1-12-12Q-8-21 4-18M-15 28Q3 24 3 12M-22-15-13-10M-22-6-14-4M-17 3-10 5" fill="none" stroke-width=".65"/>
|
||||
<path d="M-4-10Q3-18 12-10L5-5Z" fill="url(#gold)" stroke-width=".5"/>
|
||||
<path d="M5-13 4-7" fill="none" stroke="#090f0c" stroke-width="2"/>
|
||||
<path d="M13 4 17 8 19 3M23 2 25 6 28 1M12 13 15 9 18 14M23 15 25 11 28 14" fill="#ead7a5" stroke-width=".35"/>
|
||||
<path d="M14-4Q25-7 31-4M5 1 10 2M-10 12-7 14M-13 19-10 21" fill="none" stroke-width=".55"/>
|
||||
<circle cx="30" cy="-6" r="1.1" fill="#090f0c" stroke="none"/>
|
||||
<path d="M-5-36 0-41 5-36 0-32ZM-5 36 0 41 5 36 0 32Z" fill="url(#red)" stroke-width=".65"/>
|
||||
</g>
|
||||
</defs>
|
||||
<g stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M0 0H24V960H0Z" fill="#14221c"/>
|
||||
<path d="M3 0V960M21 0V960" stroke="url(#gold)" stroke-width="1.4"/>
|
||||
<path d="M6 0V960M18 0V960" stroke="#79633c" stroke-width=".4"/>
|
||||
''']
|
||||
|
||||
def path(d, stroke=GOLD, width=.65, fill="none"):
|
||||
parts.append(f'<path d="{d}" fill="{fill}" stroke="{stroke}" stroke-width="{width}"/>')
|
||||
|
||||
def circle(x, y, r, fill=GOLD):
|
||||
parts.append(f'<circle cx="{x:.2f}" cy="{y:.2f}" r="{r}" fill="{fill}"/>')
|
||||
|
||||
def use(name, x, y, angle=0, scale=1):
|
||||
parts.append(f'<use href="#{name}" transform="translate({x:.2f} {y:.2f}) rotate({angle:.2f}) scale({scale:.2f})"/>')
|
||||
|
||||
# All vertical periods divide 960, including the scrolls across the tile joins.
|
||||
for y in range(-24, 985, 24):
|
||||
path(f"M12 {y-9} 16 {y} 12 {y+9} 8 {y}Z", width=.5)
|
||||
circle(12, y, 1.2, "#dec58e")
|
||||
|
||||
for y in range(-240, 961, 240):
|
||||
d = f"M88 {y}C150 {y+60} 26 {y+180} 88 {y+240}"
|
||||
path(d, "#594525", 5)
|
||||
path(d, "url(#gold)", 3)
|
||||
path(d, "#f0dab0", .55)
|
||||
|
||||
for side, cy in ((1, y+63), (-1, y+183)):
|
||||
cx = 88 + side*20
|
||||
points = []
|
||||
for i in range(97):
|
||||
t = i / 96
|
||||
angle = -pi/2 + side*t*2*pi*1.35
|
||||
radius = 42*(1-t)+2
|
||||
points.append((cx+radius*cos(angle), cy+radius*sin(angle)))
|
||||
d = "M" + "L".join(f"{x:.2f} {yy:.2f}" for x, yy in points)
|
||||
path(d, "#594525", 2.8)
|
||||
path(d, "url(#gold)", 1.6)
|
||||
for i in (8, 22, 36, 50):
|
||||
x, yy = points[i]
|
||||
nx, ny = points[i+1]
|
||||
angle = degrees(atan2(ny-yy, nx-x)) + (145 if side == 1 else 35)
|
||||
use("leaf", x, yy, angle, .48 if i == 50 else .63)
|
||||
x, yy = points[-1]
|
||||
circle(x, yy, 3.3, "#542f2e")
|
||||
circle(x, yy, 1.5, "#e4c783")
|
||||
|
||||
for offset, side in ((16, -1), (108, 1), (136, 1), (228, -1)):
|
||||
yy = y+offset
|
||||
x = 88 + 18*sin(2*pi*offset/240)
|
||||
use("leaf", x, yy, side*56, .84)
|
||||
tx, ty = x+side*39, yy-20
|
||||
path(f"M{x:.2f} {yy}Q{tx:.2f} {yy+6} {tx:.2f} {ty}", width=.8)
|
||||
use("bud", tx, ty, side*25, .55)
|
||||
|
||||
# Small rosettes and pen flourishes fill the spaces between the main scrolls.
|
||||
for x, yy in ((45, y+91), (139, y+211)):
|
||||
for angle in range(0, 360, 45):
|
||||
a = angle*pi/180
|
||||
parts.append(f'<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="{GOLD}" stroke-width=".5" transform="translate({x} {yy}) rotate({angle})"/>')
|
||||
circle(x+13*cos(a), yy+13*sin(a), .65)
|
||||
circle(x, yy, 3.2, "#d7b66e")
|
||||
circle(x, yy, 1.1, "#f5e0ac")
|
||||
for side in (-1, 1):
|
||||
path(f"M{x+side*3} {yy+15}q{side*12} 10 {side*6} 20q{-side*5} 5 {-side*7}-1q0-4 {side*4}-2", width=.55)
|
||||
|
||||
for i in range(24):
|
||||
yy = y+i*10
|
||||
x = 158+5*sin(i*pi/6)
|
||||
circle(x, yy, .7 if i % 3 else 1.1, "#a58951")
|
||||
for yy in (y+20, y+140):
|
||||
path(f"M151 {yy-5}V{yy+5}M147 {yy}H155", width=.7)
|
||||
|
||||
for y in (120, 600):
|
||||
use("raptor", 92, y, scale=.92)
|
||||
for angle in range(0, 360, 30):
|
||||
a = angle*pi/180
|
||||
circle(92+45*cos(a), y+45*sin(a), 1.1, "#e4c783")
|
||||
|
||||
parts.append("</g></svg>\n")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
document = generate()
|
||||
root = ET.fromstring(document)
|
||||
assert root.attrib["viewBox"] == "0 0 180 960"
|
||||
ids = {element.attrib["id"] for element in root.iter() if "id" in element.attrib}
|
||||
for element in root.iter():
|
||||
if "href" in element.attrib:
|
||||
assert element.attrib["href"][1:] in ids
|
||||
assert document == generate(), "Border generation must be deterministic"
|
||||
OUTPUT.write_text(document)
|
||||
@@ -1,889 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Raptor dialect operation reference</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; --bg: #090f0c; --panel: #111e17; --fg: #e8eadb; --muted: #acb9a5; --line: #334436; --accent: #e6bb79; --fern: #a4c68d; }
|
||||
* { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.65 system-ui, sans-serif; }
|
||||
body::before, body::after { content: ""; position: absolute; inset-block: 0; width: min(420px, calc((100vw - 1100px) / 2 - 24px)); background: url("jurassic-border.svg") center top / 100% auto repeat-y; pointer-events: none; z-index: -1; }
|
||||
body { position: relative; min-height: 100vh; isolation: isolate; } body::before { left: 0; } body::after { right: 0; transform: scaleX(-1); }
|
||||
::selection { background: #445c37; color: #fff6db; }
|
||||
a { color: var(--accent); } a:focus-visible, input:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
|
||||
.skip { position: absolute; left: -9999px; } .skip:focus { left: 1rem; top: 1rem; background: var(--panel); padding: 1rem; }
|
||||
header, main { max-width: 1100px; margin: auto; padding: 2rem; } header { padding-bottom: 0; }
|
||||
h1 { font: 500 clamp(2rem, 4vw, 3rem)/1.2 Georgia, serif; color: #f2e4c6; } h2 { margin-top: 2.5rem; padding-bottom: .4rem; border-bottom: 1px solid var(--line); font-family: Georgia, serif; font-weight: 500; color: #d7d9b4; } h3 { margin: 0; font-size: 1.3rem; }
|
||||
header { border-top: 3px solid #8f794c; } header > p:first-child { font-size: .8rem; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.sources { color: var(--muted); } .toolbar { position: sticky; top: 0; z-index: 1; background: var(--bg); padding: 1rem 0; border-bottom: 1px solid var(--line); }
|
||||
input { display: block; width: 100%; font: inherit; padding: .65rem; border: 1px solid var(--line); border-radius: .4rem; background: var(--panel); color: var(--fg); }
|
||||
.contents ul { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); gap: .5rem 2rem; list-style: none; padding: 0; } .contents a { font-family: inherit; }
|
||||
h2[id], section[id] { scroll-margin-top: 10rem; }
|
||||
#operation-index ul { display: flex; flex-wrap: wrap; gap: .5rem 1.2rem; list-style: none; padding: 0; } nav a { font-family: ui-monospace, monospace; color: var(--fern); } nav a, h3 code { overflow-wrap: anywhere; }
|
||||
article { background: var(--panel); border: 1px solid var(--line); border-top-color: #596444; border-radius: .6rem; margin: 1.5rem 0; padding: 1.5rem; scroll-margin-top: 10rem; box-shadow: 0 8px 28px #0002; }
|
||||
dt { font-weight: 700; margin-top: 1rem; color: var(--fern); } dd { margin-left: 0; } code { font-family: ui-monospace, monospace; font-size: .92em; }
|
||||
pre { overflow-x: auto; padding: 1rem; background: var(--bg); border: 1px solid var(--line); border-radius: .3rem; line-height: 1.5; }
|
||||
table { border-collapse: collapse; width: 100%; } th, td { text-align: left; border-bottom: 1px solid var(--line); padding: .6rem; vertical-align: top; overflow-wrap: anywhere; }
|
||||
[hidden] { display: none !important; } @media (max-width: 600px) { header, main { padding: 1rem; } article { padding: 1rem; } }
|
||||
@media (max-width: 1279px) { body::before, body::after { display: none; } }
|
||||
@media print { body::before, body::after, .toolbar, .skip { display: none; } article { break-inside: avoid; } article[hidden], nav li[hidden] { display: block !important; } }
|
||||
</style>
|
||||
</head><body><a class="skip" href="#reference">Skip to operation reference</a>
|
||||
<header><p><a href="../../README.md">Raptor repository</a> / Developer reference</p>
|
||||
<h1>Raptor dialect reference</h1></header>
|
||||
<main id="reference">
|
||||
<nav class="contents" aria-label="Table of contents">
|
||||
<h2 id="contents">Contents</h2>
|
||||
<ul>
|
||||
<li><a href="#reading">Values, operations, and types</a></li>
|
||||
<li><a href="#compact">Multiple results and compact lists</a></li>
|
||||
<li><a href="#planning">Planning operations and attributes</a></li>
|
||||
<li><a href="#compute-regions">Compute regions and bindings</a></li>
|
||||
<li><a href="#graph-batches">Graph batches and fragment slots</a></li>
|
||||
<li><a href="#input-representations">Compute input representations</a></li>
|
||||
<li><a href="#scheduling">Scheduled lanes and physical cores</a></li>
|
||||
<li><a href="#destinations">PIM destinations and storage</a></li>
|
||||
<li><a href="#memory-units">Memory offsets and units</a></li>
|
||||
<li><a href="#communication">Transfers and synchronization</a></li>
|
||||
<li><a href="#contracts">Verification and code generation</a></li>
|
||||
<li><a href="#spatial-index">Spatial operation index</a></li>
|
||||
<li><a href="#pim-index">PIM operation index</a></li>
|
||||
</ul></nav>
|
||||
|
||||
<section id="reading"><h2>Values, operations, and types</h2>
|
||||
<p>The Spatial dialect describes computations with <code>spat.</code> operations. For example, <a href="#spat.vadd"><code>spat.vadd</code></a> adds two tensors element by element:</p>
|
||||
<pre data-example="addition"><code>%y = spat.vadd %a, %b : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre>
|
||||
<p>The operands <code>%a</code> and <code>%b</code> are values defined earlier in the enclosing function or <a href="#compute-regions">region</a>. The operation produces <code>%y</code>, a new single static assignment (SSA) value. Each SSA value has one definition and can have several uses.</p>
|
||||
<p>After the colon, the two types in parentheses describe the operands in order. The type after <code>-></code> describes the result. Here, every value has type <code>tensor<1x4xf32></code>: a rank-2 tensor with one row, four columns, and 32-bit floating-point elements.</p>
|
||||
<p>The result has the same shape as the operands because addition produces one value for each pair of elements. Other operations can change the shape or produce several results.</p>
|
||||
</section>
|
||||
|
||||
<section id="compact"><h2>Multiple results and compact lists</h2>
|
||||
<p><a href="#spat.extract_rows"><code>spat.extract_rows</code></a> produces a separate SSA value for each matrix row. This example extracts two rows and joins them along their column axis:</p>
|
||||
<pre data-example="rows"><code>%rows:2 = spat.extract_rows %matrix : tensor<2x4xf32> -> tensor<1x4xf32> x2
|
||||
%joined = spat.concat axis 1 %rows#0, %rows#1 : (tensor<1x4xf32> x2) -> tensor<1x8xf32></code></pre>
|
||||
<p><code>%rows:2</code> names a group of two results. <code>%rows#0</code> selects the first result, and <code>%rows#1</code> selects the second. Each result is a rank-2 tensor with one row and four columns.</p>
|
||||
<p>The suffix <code>x2</code> repeats the preceding type twice. Thus, the input type list for <a href="#spat.concat"><code>spat.concat</code></a> contains two <code>tensor<1x4xf32></code> types. The <code>x</code> characters inside that tensor type separate its dimensions and element type.</p>
|
||||
<p>These operations use the <a href="../../src/PIM/Common/IR/CompactAsmUtils.hpp">compact list syntax</a> for repeated types and operands. Integer ranges in core lists use the same helpers; the <a href="#scheduling">core batch example</a> shows their bounds.</p>
|
||||
</section>
|
||||
|
||||
<section id="planning"><h2>Planning operations and attributes</h2>
|
||||
<p>Before it creates individual compute regions, the compiler records model operations with their logical tensor shapes. For example, <a href="#spat.add_plan"><code>spat.add_plan</code></a> records addition in NCHW coordinates:</p>
|
||||
<pre data-example="plan"><code>%y = "spat.add_plan"(%a, %b) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>, tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32></code></pre>
|
||||
<p>In NCHW order, the dimensions count model examples (N), channels (C), height (H), and width (W). The example has one model example, two channels, three rows, and four columns.</p>
|
||||
<p>The <code><{...}></code> dictionary holds operation properties known at compile time. Here, <code>logicalLayout</code> identifies the coordinate order. Planning operations use this quoted operation form; their entries show the properties for each operation.</p>
|
||||
<p>The planner selects a physical representation separately from these logical coordinates. <a href="#spat.materialize_layout"><code>spat.materialize_layout</code></a> makes a physical layout conversion explicit. The <a href="../compiler/spatial-layouts.md">layout reference</a> lists supported representations and conversions.</p>
|
||||
</section>
|
||||
|
||||
<section id="compute-regions"><h2>Compute regions and bindings</h2>
|
||||
<p>The compiler lowers planned work into compute regions. A region contains operations that use bound inputs and return results through <a href="#spat.yield"><code>spat.yield</code></a>. This <a href="#spat.graph_compute"><code>spat.graph_compute</code></a> multiplies an input row by a constant matrix:</p>
|
||||
<pre data-example="weighted"><code>%w = arith.constant dense<1.0> : tensor<4x3xf32>
|
||||
%y = spat.graph_compute [%warg] = [%w] (%arg) = (%x) crossbarWeights 1 : [tensor<4x3xf32>] (tensor<1x4xf32>) -> tensor<1x3xf32> {
|
||||
%v = spat.wvmm[%warg](%arg) : (tensor<4x3xf32>, tensor<1x4xf32>) -> tensor<1x3xf32>
|
||||
spat.yield %v : tensor<1x3xf32>
|
||||
}</code></pre>
|
||||
<p>The square-bracket binding gives the outer constant <code>%w</code> the body name <code>%warg</code>. The parenthesis binding gives the outer input <code>%x</code> the body name <code>%arg</code>. The type lists after the colon follow the same weight-then-input order.</p>
|
||||
<p>The braces enclose the region body. Within that body, <a href="#spat.wvmm"><code>spat.wvmm</code></a> takes the bound matrix and input row. Its result <code>%v</code> becomes the outer result <code>%y</code> through <code>spat.yield</code>.</p>
|
||||
<p><code>crossbarWeights 1</code> reports one distinct resident weight used by the body. The printer derives this count from the computation. Physical weight planning later maps resident weights to crossbar resources.</p>
|
||||
<p>The graph and scheduled compute operations use these bindings. PIM core regions also bind resident weights, as described under <a href="#pim.core"><code>pim.core</code></a>.</p>
|
||||
</section>
|
||||
|
||||
<section id="graph-batches"><h2>Graph batches and fragment slots</h2>
|
||||
<p><a href="#spat.graph_compute_batch"><code>spat.graph_compute_batch</code></a> expresses several lane computations with one body. In this example, two lanes apply ReLU to different four-column slices of one input:</p>
|
||||
<pre data-example="graph-batch"><code>%fragments = spat.graph_compute_batch %lane = 0 to 2 [] = [] (%arg) = (%x) shared_outs(%out) crossbarWeights 0 : [] (tensor<1x8xf32>) -> tensor<2x1x4xf32> {
|
||||
%offset = affine.apply affine_map<(d0) -> (d0 * 4)>(%lane)
|
||||
%fragment = tensor.extract_slice %arg[0, %offset] [1, 4] [1, 1] : tensor<1x8xf32> to tensor<1x4xf32>
|
||||
%v = spat.relu(%fragment) : tensor<1x4xf32> -> tensor<1x4xf32>
|
||||
spat.in_parallel {
|
||||
tensor.parallel_insert_slice %v into %out[%lane, 0, 0] [1, 1, 4] [1, 1, 1] : tensor<1x4xf32> into tensor<2x1x4xf32>
|
||||
}
|
||||
}</code></pre>
|
||||
<p><code>%lane = 0 to 2</code> gives the lane indices 0 and 1; the upper bound is exclusive. The lane argument has type <code>index</code>, an integer SSA type used here to calculate slice offsets. Lane 0 reads columns 0–3, and lane 1 reads columns 4–7.</p>
|
||||
<p>Each lane produces a <code>tensor<1x4xf32></code> fragment. <code>shared_outs(%out)</code> names the body output argument. Inside <a href="#spat.in_parallel"><code>spat.in_parallel</code></a>, each insertion publishes one fragment into slot <code>%lane</code>.</p>
|
||||
<p>The batch produces one SSA result, <code>%fragments</code>, with type <code>tensor<2x1x4xf32></code>. Its leading dimension counts two fragment publications. The remaining dimensions describe one fragment. For N lanes producing fragments of type F, each graph result has shape <code>[N] + shape(F)</code>.</p>
|
||||
<p>This is a <strong>physical fragment collection</strong> in the graph IR. It describes SSA publications before memory allocation or core placement. Its slots need an explicit mapping to logical tensor coordinates. For this example, <a href="#spat.blueprint"><code>spat.blueprint</code></a> places the two fragments next to each other:</p>
|
||||
<pre data-example="reconstruction"><code>%logical = spat.blueprint fragments(%fragments) layout nchw physical fragmented offsets [0, 0, 0, 4] sizes [1, 4, 1, 4] map explicit mode fragment_assembly operandIndices [0, 0] sourceSlots [0, 1] sourceOffsets [0, 0] strides [1, 1, 1, 1] conflict disjoint coverage complete : (tensor<2x1x4xf32>) -> tensor<1x8xf32></code></pre>
|
||||
<p>The flattened <code>offsets</code> and <code>sizes</code> lists contain one rank-2 destination slice per fragment:</p>
|
||||
<table><thead><tr><th>Source slot</th><th>Logical offset</th><th>Slice size</th><th>Logical columns</th></tr></thead><tbody>
|
||||
<tr><td>0</td><td>[0, 0]</td><td>[1, 4]</td><td>0–3</td></tr>
|
||||
<tr><td>1</td><td>[0, 4]</td><td>[1, 4]</td><td>4–7</td></tr>
|
||||
</tbody></table>
|
||||
<p>The result <code>%logical</code> has shape 1×8 because this descriptor defines that reconstruction. The <a href="../../.agents/invariants/GRAPH_COMPUTE_BATCH_INVARIANT.md">graph fragment invariant</a> specifies publication and reconstruction requirements for every graph batch result.</p>
|
||||
</section>
|
||||
|
||||
<section id="input-representations"><h2>Compute input representations</h2>
|
||||
<p>The graph batch above binds one logical <code>tensor<1x8xf32></code> input and returns a physical fragment collection. Thus, its input and result have different representations. A later compute can consume either representation, provided its body selects the correct coordinates:</p>
|
||||
<table><thead><tr><th>Input example</th><th>How the body accesses it</th><th>Related implementation</th></tr></thead><tbody>
|
||||
<tr><td>Logical <code>%x : tensor<1x8xf32></code></td><td>The graph example extracts four columns using a logical column offset. The input has no leading lane dimension.</td><td><a href="../../src/PIM/Conversion/ONNXToSpatial/Patterns/Math/Gemm.cpp">GEMM lowering</a> similarly binds logical matrix inputs and selects tiles.</td></tr>
|
||||
<tr><td>Physical <code>%fragments : tensor<2x1x4xf32></code></td><td>Dimension 0 selects a published fragment slot. The remaining dimensions address elements within that fragment.</td><td><a href="../../src/PIM/Conversion/ONNXToSpatial/Common/ComputeRegionBuilder.hpp">mapGraphBatchFragments</a> creates consumers that select one fragment per lane.</td></tr>
|
||||
<tr><td>Logical <code>%logical : tensor<1x8xf32></code> described by a blueprint</td><td>The blueprint retains the mapping from logical slices to physical source slots. The logical type alone does not establish dense physical storage.</td><td><a href="../../src/PIM/Conversion/ONNXToSpatial/Common/RowStripLayoutUtils.cpp">Row-strip lowering</a> follows blueprint mappings to their fragment sources.</td></tr>
|
||||
</tbody></table>
|
||||
<p>The input binding preserves the complete operand type. A consumer lane can select several producer fragments, and several consumer lanes can read the same fragment. Producer slot count and consumer lane count can therefore differ. Shared bindings describe SSA reuse; physical memory and crossbar allocation are later decisions.</p>
|
||||
</section>
|
||||
|
||||
<section id="scheduling"><h2>Scheduled lanes and physical cores</h2>
|
||||
<p>Scheduling assigns graph computations to physical cores and introduces explicit communication between cores. <a href="#spat.scheduled_compute"><code>spat.scheduled_compute</code></a> describes one scheduled computation; <a href="#spat.scheduled_compute_batch"><code>spat.scheduled_compute_batch</code></a> groups equivalent scheduled instances.</p>
|
||||
<p>The following identities describe different parts of that transition:</p>
|
||||
<table><thead><tr><th>Identity</th><th>Meaning</th></tr></thead><tbody>
|
||||
<tr><td>Graph lane</td><td>One instance of a graph batch body. In the ReLU example, lane 1 processes columns 4–7.</td></tr>
|
||||
<tr><td>Fragment slot</td><td>One publication position in a graph result. The example publishes lane 1 into slot 1; other batches can use a static permutation.</td></tr>
|
||||
<tr><td>Scheduled lane</td><td>One instance in a scheduled batch. Scheduling determines which graph work belongs to that instance.</td></tr>
|
||||
<tr><td>Physical core</td><td>The hardware core assigned to execute an instance. A placement array maps lanes to core IDs.</td></tr>
|
||||
</tbody></table>
|
||||
<p>At the processing-in-memory (PIM) stage, <a href="#pim.core_batch"><code>pim.core_batch</code></a> retains a common body for several core streams. This minimal example contains only their terminating instruction:</p>
|
||||
<pre data-example="core-batch"><code>pim.core_batch %lane = 0 to 4 [] = [] () = () coreIds [0 to 3] : [] () -> () {
|
||||
pim.halt
|
||||
}</code></pre>
|
||||
<p>The lane range <code>0 to 4</code> is exclusive and creates four instances. The integer list <code>[0 to 3]</code> is inclusive and expands to <code>[0, 1, 2, 3]</code>. Its entries assign those instances to physical cores. Each stream ends with <a href="#pim.halt"><code>pim.halt</code></a>.</p>
|
||||
<p>Scheduled batches describe placed execution and communication. Their result shapes follow that execution contract; the graph-only fragment-slot rule does not apply to them.</p>
|
||||
</section>
|
||||
|
||||
<section id="destinations"><h2>PIM destinations and storage</h2>
|
||||
<p>PIM arithmetic operations write into an explicit destination. For example, <a href="#pim.vrelu"><code>pim.vrelu</code></a> writes the ReLU result into <code>%dst</code>:</p>
|
||||
<pre data-example="destination"><code>%y = pim.vrelu(%x, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre>
|
||||
<p><code>%y</code> is the updated destination value. Operations that use the result consume <code>%y</code>. During bufferization, tensor values become memory references:</p>
|
||||
<pre data-example="bufferized"><code>%y = pim.vrelu(%x, %dst) : (memref<1x4xf32>, memref<1x4xf32>) -> memref<1x4xf32></code></pre>
|
||||
<p><code>memref<1x4xf32></code> describes addressable storage for the same element shape. The result refers to the destination storage. Memory planning assigns local allocations and addresses before code generation.</p>
|
||||
<p>Partial writes preserve destination bytes outside the written range. Each operation's constraints specify its storage and overlap requirements; destination binding alone does not permit arbitrary input/output overlap.</p>
|
||||
</section>
|
||||
|
||||
<section id="memory-units"><h2>Memory offsets and units</h2>
|
||||
<p><a href="#pim.memcp"><code>pim.memcp</code></a> copies a byte range between local buffers. This example defines zero byte offsets and copies four 32-bit floating-point elements:</p>
|
||||
<pre data-example="copy"><code>%zero = arith.constant 0 : index
|
||||
%y = pim.memcp[%zero, %zero](%dst, %src) {size = 16 : i32} : memref<1x4xf32>, memref<1x4xf32> -> memref<1x4xf32></code></pre>
|
||||
<p>The first offset belongs to the destination, and the second belongs to the source. Both are SSA operands of type <code>index</code>. The <code>{size = 16 : i32}</code> attribute dictionary gives a compile-time byte count with integer type <code>i32</code>. Four <code>f32</code> elements occupy 16 bytes.</p>
|
||||
<p><a href="#pim.vmv"><code>pim.vmv</code></a> uses byte offsets too, but its source stride and length count elements. The following copy selects every second source element:</p>
|
||||
<pre data-example="gather"><code>%stride = arith.constant 2 : index
|
||||
%y = pim.vmv[%zero, %zero, %stride](%dst, %src) {length = 4 : i32} : memref<1x4xf32>, memref<1x8xf32> -> memref<1x4xf32></code></pre>
|
||||
<p>Here, <code>%zero</code> has the definition shown above. Source positions 0, 2, 4, and 6 produce four contiguous destination elements. For <code>f32</code>, the stride advances eight bytes between source elements.</p>
|
||||
<p>Vector arithmetic also measures instruction lengths in elements. Copy and transfer operations measure their sizes in bytes. Backend configuration determines element bitwidths; the <a href="#contracts">code generation requirements</a> apply to both groups.</p>
|
||||
</section>
|
||||
|
||||
<section id="communication"><h2>Transfers and synchronization</h2>
|
||||
<p>Scheduled work uses <a href="#spat.channel_send"><code>spat.channel_send</code></a> and <a href="#spat.channel_receive"><code>spat.channel_receive</code></a> for explicit dataflow between cores. PIM lowering turns these transfers into core instructions. For a direct transfer, the source sends a payload and the target receives the same byte count:</p>
|
||||
<pre data-example="send"><code>// Source core; %target is the target core ID.
|
||||
pim.send(%x, %target) {size = 16 : i32} : tensor<1x4xf32> -> ()</code></pre>
|
||||
<pre data-example="receive"><code>// Target core; %source is the source core ID, and %zero is a byte offset.
|
||||
%y = pim.receive[%zero](%dst, %source) {size = 16 : i32} : tensor<1x4xf32> -> tensor<1x4xf32></code></pre>
|
||||
<p>The peer operands have type <code>index</code> and must resolve statically. The sender and receiver must agree on core IDs, byte count, and transfer order. Their <a href="#pim.send">operation entries</a> give the storage requirements.</p>
|
||||
<p>Host-routed transfers use a shared host slot instead. <a href="#spat.host_store_sync"><code>spat.host_store_sync</code></a> stores a payload and signals its availability. <a href="#spat.host_wait_load"><code>spat.host_wait_load</code></a> waits for that signal before loading the payload.</p>
|
||||
<p>The signal and wait use the following PIM operations in their respective core streams:</p>
|
||||
<pre data-example="signal"><code>// Writer core; signal the event register on %target.
|
||||
pim.sync %target event %event</code></pre>
|
||||
<pre data-example="wait"><code>// Reader core; wait for the expected number of signals.
|
||||
pim.wait %event value %count</code></pre>
|
||||
<p><a href="#pim.sync"><code>pim.sync</code></a> increments a register local to the target core. <a href="#pim.wait"><code>pim.wait</code></a> proceeds when that register equals <code>%count</code>, then resets it to zero. These operands must resolve to static integer values.</p>
|
||||
<p>Registers start at zero and persist across stream restarts. Repeated execution must protect each host slot until all readers finish with its previous contents. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization contract</a> defines the READY/FREE protocol, restart ordering, and register separation required for that reuse.</p>
|
||||
</section>
|
||||
|
||||
<section id="contracts"><h2>Verification and code generation</h2>
|
||||
<p>The examples follow the compiler stages: logical plans, graph computations, scheduled work, PIM tensors, and bufferized memory operations. Code generation then emits the per-core instruction streams. The <a href="../compiler/architecture.md">compiler architecture</a> describes the passes between these stages.</p>
|
||||
<p>The Operation Definition Specification (ODS) declares operand types and traits used to generate basic checks. Operation-specific verifiers enforce additional constraints.</p>
|
||||
<p>Each operation entry separates its enforced checks from requirements on producers and later passes. <strong>Verified</strong> identifies checks in the operation verifier, parser, or declared traits. <strong>Assumed</strong> identifies requirements that the producer or later lowering must satisfy. Acceptance by an operation verifier alone does not establish executable PIM code.</p>
|
||||
<p>For emission, address, lane, peer, and event expressions must resolve statically. Code generation evaluates supported constant loops and lane expressions before emitting instructions. Local storage must have an explicit memory plan with valid contiguous addresses.</p>
|
||||
<p>Memory verification requires nonnegative addresses, four-byte allocation alignment, and ranges within the local arena. Allocations that are live simultaneously must not overlap. Weight resources must be compile-time constants materialized for the selected target. Numeric element types must be supported by the executing backend.</p>
|
||||
<p>The entries below apply these common requirements to each operation. Their source links identify the assembly, verification, and lowering implementations.</p>
|
||||
</section>
|
||||
|
||||
<div class="toolbar"><label for="search">Find an operation, input, or constraint</label><input id="search" type="search" placeholder="e.g. graph_compute_batch, byte, blueprint" autocomplete="off" disabled><span id="count" role="status" aria-live="polite">All 63 operations</span><noscript><p>Use your browser’s Find command to search.</p></noscript></div>
|
||||
<nav id="operation-index" aria-label="Operation index">
|
||||
|
||||
<h2 id="spatial-index">Spatial operation index</h2><ul>
|
||||
<li><a href="#spat.add_plan">spat.add_plan</a></li>
|
||||
<li><a href="#spat.bias_add_plan">spat.bias_add_plan</a></li>
|
||||
<li><a href="#spat.block_yield">spat.block_yield</a></li>
|
||||
<li><a href="#spat.blueprint">spat.blueprint</a></li>
|
||||
<li><a href="#spat.channel_receive">spat.channel_receive</a></li>
|
||||
<li><a href="#spat.channel_send">spat.channel_send</a></li>
|
||||
<li><a href="#spat.concat">spat.concat</a></li>
|
||||
<li><a href="#spat.concat_plan">spat.concat_plan</a></li>
|
||||
<li><a href="#spat.conv2d_plan">spat.conv2d_plan</a></li>
|
||||
<li><a href="#spat.deferred_communication">spat.deferred_communication</a></li>
|
||||
<li><a href="#spat.deferred_source_select">spat.deferred_source_select</a></li>
|
||||
<li><a href="#spat.extract_rows">spat.extract_rows</a></li>
|
||||
<li><a href="#spat.flatten_plan">spat.flatten_plan</a></li>
|
||||
<li><a href="#spat.global_average_pool_plan">spat.global_average_pool_plan</a></li>
|
||||
<li><a href="#spat.graph_compute">spat.graph_compute</a></li>
|
||||
<li><a href="#spat.graph_compute_batch">spat.graph_compute_batch</a></li>
|
||||
<li><a href="#spat.host_store_sync">spat.host_store_sync</a></li>
|
||||
<li><a href="#spat.host_wait_load">spat.host_wait_load</a></li>
|
||||
<li><a href="#spat.in_parallel">spat.in_parallel</a></li>
|
||||
<li><a href="#spat.materialize_layout">spat.materialize_layout</a></li>
|
||||
<li><a href="#spat.max_pool2d_plan">spat.max_pool2d_plan</a></li>
|
||||
<li><a href="#spat.relu">spat.relu</a></li>
|
||||
<li><a href="#spat.relu_plan">spat.relu_plan</a></li>
|
||||
<li><a href="#spat.resize_nearest_plan">spat.resize_nearest_plan</a></li>
|
||||
<li><a href="#spat.scheduled_compute">spat.scheduled_compute</a></li>
|
||||
<li><a href="#spat.scheduled_compute_batch">spat.scheduled_compute_batch</a></li>
|
||||
<li><a href="#spat.sigmoid">spat.sigmoid</a></li>
|
||||
<li><a href="#spat.silu_plan">spat.silu_plan</a></li>
|
||||
<li><a href="#spat.softmax">spat.softmax</a></li>
|
||||
<li><a href="#spat.sync">spat.sync</a></li>
|
||||
<li><a href="#spat.vadd">spat.vadd</a></li>
|
||||
<li><a href="#spat.vavg">spat.vavg</a></li>
|
||||
<li><a href="#spat.vmax">spat.vmax</a></li>
|
||||
<li><a href="#spat.vmul">spat.vmul</a></li>
|
||||
<li><a href="#spat.vsub">spat.vsub</a></li>
|
||||
<li><a href="#spat.vvdmul">spat.vvdmul</a></li>
|
||||
<li><a href="#spat.wait">spat.wait</a></li>
|
||||
<li><a href="#spat.wvmm">spat.wvmm</a></li>
|
||||
<li><a href="#spat.yield">spat.yield</a></li>
|
||||
</ul>
|
||||
<h2 id="pim-index">PIM operation index</h2><ul>
|
||||
<li><a href="#pim.concat">pim.concat</a></li>
|
||||
<li><a href="#pim.core">pim.core</a></li>
|
||||
<li><a href="#pim.core_batch">pim.core_batch</a></li>
|
||||
<li><a href="#pim.halt">pim.halt</a></li>
|
||||
<li><a href="#pim.memcp">pim.memcp</a></li>
|
||||
<li><a href="#pim.memcp_dh">pim.memcp_dh</a></li>
|
||||
<li><a href="#pim.memcp_hd">pim.memcp_hd</a></li>
|
||||
<li><a href="#pim.receive">pim.receive</a></li>
|
||||
<li><a href="#pim.send">pim.send</a></li>
|
||||
<li><a href="#pim.sync">pim.sync</a></li>
|
||||
<li><a href="#pim.transpose">pim.transpose</a></li>
|
||||
<li><a href="#pim.vavg">pim.vavg</a></li>
|
||||
<li><a href="#pim.vmm">pim.vmm</a></li>
|
||||
<li><a href="#pim.vmv">pim.vmv</a></li>
|
||||
<li><a href="#pim.vrelu">pim.vrelu</a></li>
|
||||
<li><a href="#pim.vsigm">pim.vsigm</a></li>
|
||||
<li><a href="#pim.vsoftmax">pim.vsoftmax</a></li>
|
||||
<li><a href="#pim.vtanh">pim.vtanh</a></li>
|
||||
<li><a href="#pim.vvadd">pim.vvadd</a></li>
|
||||
<li><a href="#pim.vvdmul">pim.vvdmul</a></li>
|
||||
<li><a href="#pim.vvmax">pim.vvmax</a></li>
|
||||
<li><a href="#pim.vvmul">pim.vvmul</a></li>
|
||||
<li><a href="#pim.vvsub">pim.vvsub</a></li>
|
||||
<li><a href="#pim.wait">pim.wait</a></li>
|
||||
</ul>
|
||||
</nav><section aria-label="Operation details">
|
||||
<article id="spat.add_plan">
|
||||
<h3><a href="#spat.add_plan"><code>spat.add_plan</code></a> — Plan element-wise addition</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.add_plan"(%a, %b) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>, tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): matching NCHW tensors, each with shape 1×2×3×4 in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Adds corresponding elements. In the example, each of the 24 output elements is the sum of two input elements.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: static ranked rank-4 tensors with identical complete types; nchw layout.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.bias_add_plan">
|
||||
<h3><a href="#spat.bias_add_plan"><code>spat.bias_add_plan</code></a> — Plan channel bias addition</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.bias_add_plan"(%x, %bias) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>, tensor<2xf32>) -> tensor<1x2x3x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): an NCHW tensor with shape 1×2×3×4. bias (<code>%bias</code>): two channel bias values in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Adds a scalar or per-channel bias across the input spatial coordinates. Here, bias[0] applies to channel 0 and bias[1] applies to channel 1.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: static ranked tensors; input/output complete types identical and rank 4; bias element type matches; nchw layout. Allowed bias shapes: scalar rank 0, [C], [1,C], [1,C,1,1]. Other broadcasting shapes are rejected.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.block_yield">
|
||||
<h3><a href="#spat.block_yield"><code>spat.block_yield</code></a> — Structural scheduled block terminator</h3>
|
||||
<pre data-field="syntax"><code>spat.block_yield :</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">outputs: optional values forwarded to a successor block. A successor is written as <code>next ^bb</code> after those values. The example has neither values nor a successor.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results on this operation.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Ends a structural scheduled block. With a successor, it forwards the operands to that block. The shown empty form ends the structural sequence. The parent restriction below limits its use.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: parent is <a href="#spat.scheduled_compute"><code>spat.scheduled_compute</code></a>; at most one successor; forwarded operand count and types match successor arguments. However, the scheduled-compute verifier requires one block ending in <a href="#spat.yield"><code>spat.yield</code></a>. Therefore, this declared structural terminator is not accepted in an ordinarily verified scheduled_compute body.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.blueprint">
|
||||
<h3><a href="#spat.blueprint"><code>spat.blueprint</code></a> — Describe logical reconstruction</h3>
|
||||
<pre data-field="syntax"><code>%logical = spat.blueprint fragments(%y) layout nchw physical fragmented offsets [0, 0, 0, 4] sizes [1, 4, 1, 4] map explicit mode fragment_assembly operandIndices [0, 0] sourceSlots [0, 1] sourceOffsets [0, 0] strides [1, 1, 1, 1] conflict disjoint coverage complete : (tensor<2x1x4xf32>) -> tensor<1x8xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%y</code>): the first fragment collection. Optional fragments add further collections to the printed <code>fragments(...)</code> list. Here, one collection contains two 1×4 fragments. See the <a href="#graph-batches">publication and reconstruction example</a>.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%logical</code>): the reconstructed logical tensor. Here, the descriptor places two 1×4 source fragments into a 1×8 result. The <a href="#graph-batches">reconstruction table</a> shows their destination coordinates.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>layout</code> and <code>physical</code> print logicalLayout and physicalLayout. <code>offsets</code> and <code>sizes</code> print flattened destination slices in logical element coordinates. <code>map</code> names indexMap. <code>mode</code> selects physical_view or fragment_assembly. In fragment_assembly, operandIndices selects source collections, and sourceSlots selects their publications. sourceOffsets gives flat element offsets within each slot. <code>strides</code> prints fragmentStrides. <code>conflict</code> and <code>coverage</code> print conflictPolicy and coveragePolicy, which control destination overlap and coverage. The <a href="#graph-batches">mapping table</a> expands the example destination geometry.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Maps fragment publications to logical tensor regions. Here, source slot 0 supplies columns 0–3, and slot 1 supplies columns 4–7. Reversing sourceSlots changes that placement while preserving the collection type. The fragment_assembly mode records explicit source and destination geometry. The physical_view mode describes a collection with one leading slot dimension. Reconstruction describes placement; arithmetic combinations require a following compute operation. Later lowering determines storage and any required data movement.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints"><p><strong>Verified geometry.</strong> Forms with destination geometry require offset and size lists of equal length, divisible by the positive output rank. Each destination slice stays within logical bounds. Contiguous row-major mappings also require canonical geometry and physical ordering.</p>
|
||||
<p><strong>physical_view.</strong> Input and output are static ranked tensors, and input rank equals output rank plus one. Layouts are known. This form uses one input collection, empty offset/size arrays, and no assembly metadata.</p>
|
||||
<p><strong>fragment_assembly.</strong> Physical operands are static ranked tensors with rank equal to output rank plus one. Operand indices and source slots are valid, and source element offsets are nonnegative. Source slices fit each fragment and match the output element type. Every operand contributes at least one fragment.</p>
|
||||
<p>Destination strides are one, and conflictPolicy is disjoint. coveragePolicy can be complete or partial. Destination slices are disjoint; complete coverage fills the entire static output. Arithmetic combinations belong in compute operations, as described under <a href="#graph-batches">graph reconstruction</a>.</p></dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.channel_receive">
|
||||
<h3><a href="#spat.channel_receive"><code>spat.channel_receive</code></a> — Receive a logical payload</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.channel_receive channel %channel from %source to %target : tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">channelId (<code>%channel</code>), sourceCoreId (<code>%source</code>), and targetCoreId (<code>%target</code>): index SSA operands for this transfer.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output: received payload.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required. The channel and endpoint IDs appear as SSA operands in the example.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Receives the complete payload from the paired <a href="#spat.channel_send"><code>spat.channel_send</code></a>. The result type specifies its shape and element type. Target lowering implements the pair with core-addressed SEND/RECV instructions.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped and index operand types; this operation has no custom verifier. Scheduling and communication verification check endpoint pairing, payload types and sizes, core mappings, transfer order, and deadlock freedom. ID expressions must resolve statically at emission. Lane bodies use these scalar channel operations.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.channel_send">
|
||||
<h3><a href="#spat.channel_send"><code>spat.channel_send</code></a> — Send a logical payload</h3>
|
||||
<pre data-field="syntax"><code>spat.channel_send %x channel %channel from %source to %target : tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete payload. channelId (<code>%channel</code>), sourceCoreId (<code>%source</code>), and targetCoreId (<code>%target</code>): index SSA operands for this transfer.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results; communication effect.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required. The channel and endpoint IDs appear as SSA operands in the example.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Sends the complete payload on a logical channel. Pair it with <a href="#spat.channel_receive"><code>spat.channel_receive</code></a> using the same channel and endpoints. Target lowering implements the pair with core-addressed SEND/RECV instructions.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped and index operand types; this operation has no custom verifier. Scheduling and communication verification check endpoint pairing, payload types and sizes, core mappings, transfer order, and deadlock freedom. ID expressions must resolve statically at emission. Lane bodies use these scalar channel operations.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.concat">
|
||||
<h3><a href="#spat.concat"><code>spat.concat</code></a> — Join tensors along one axis</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.concat axis 1 %a, %b : (tensor<1x2xf32> x2) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">inputs (<code>%a</code>, <code>%b</code>): ordered shaped values, each 1×2 in the example. The compact type suffix <code>x2</code> is explained under <a href="#compact">multiple results and compact lists</a>.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output: concatenation of the inputs along axis.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">axis: required i64 printed after axis; cannot also be supplied in the attribute dictionary.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Joins inputs in operand order along axis. Here, axis 1 joins two 1×2 tensors into one 1×4 tensor. Other dimensions preserve their coordinates.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: at least one input and an axis in [0,outputRank). Producers must normalize negative axes before this operation. Input ranks and element types match the output. Static non-axis dimensions match. When all axis sizes are static, their sum equals the output axis size. Dynamic dimensions receive the comparisons that can be established statically. The parser checks expanded input and type counts. Tensor and memref container kinds need not all match in the Spatial verifier. Code generation requires static addressable storage.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.concat_plan">
|
||||
<h3><a href="#spat.concat_plan"><code>spat.concat_plan</code></a> — Plan channel concatenation</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.concat_plan"(%a, %b) <{axis = 1 : i64, logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>, tensor<1x2x3x4xf32>) -> tensor<1x4x3x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">inputs (<code>%a</code>, <code>%b</code>): NCHW tensors in concatenation order. Each example input has two channels and spatial shape 3×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>. <code>axis = 1 : i64</code> selects the channel dimension.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Joins the inputs along the channel axis. The example places the two channels of %a before the two channels of %b.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: nchw layout, a static rank-4 output, axis 1, and at least one input. Input ranks and element types match the output. Static non-axis dimensions match. When input axis sizes are static, their sum equals the output axis size. Layout selection and lowering can require further static geometry.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.conv2d_plan">
|
||||
<h3><a href="#spat.conv2d_plan"><code>spat.conv2d_plan</code></a> — Plan a grouped 2D convolution</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.conv2d_plan"(%x, %weight) <{pads = array<i64: 0, 0, 0, 0>, strides = array<i64: 1, 1>, dilations = array<i64: 1, 1>, group = 1 : i64, logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x4x4xf32>, tensor<3x2x3x3xf32>) -> tensor<1x3x2x2xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): shape [N,Cin,H,W], here [1,2,4,4]. weight (<code>%weight</code>): shape [Cout,Cin/group,Kh,Kw], here [3,2,3,3]. An optional bias supplies output-channel offsets.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>. <code>pads</code>: [top,left,bottom,right] in elements. <code>strides</code> and <code>dilations</code>: [height,width] element steps. The <code>array<i64: ...></code> notation stores these integer lists. <code>group</code>: number of channel groups; 1 in the example.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Computes NCHW cross-correlation. For each spatial axis, output = floor((input+padBegin+padEnd-dilation*(kernel-1)-1)/stride)+1. The example uses 3×3 kernels and zero padding, reducing each spatial axis from four to two. The three filters combine both input channels into three output channels.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: rank-4 tensor input, weight, and output; matching element types; four pads; two strides; two dilations; group>=1; known logical layout. Optional bias is ranked and has a matching element type. Assumed: positive strides and dilations, valid channel groups, compatible bias shape, and output dimensions that satisfy the formula above. Selected lowering also requires supported static geometry.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.deferred_communication">
|
||||
<h3><a href="#spat.deferred_communication"><code>spat.deferred_communication</code></a> — Describe a future payload transfer</h3>
|
||||
<p>The custom form below appears in compiler dumps. Its printer omits source block-argument names, so use the explicit generic form below for parseable input.</p>
|
||||
<pre data-field="syntax"><code>%y = spat.deferred_communication %x : (tensor<1x4xf32>) -> tensor<1x4xf32> {
|
||||
spat.yield %arg0 : tensor<1x4xf32>
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">sources (<code>%x</code>): published shaped values bound to source arguments in the body. The example body refers to its source as <code>%arg0</code>. Grouped specialization adds a final index argument.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">One SSA payload value. The ordinary form returns the body fragment type. Grouped specialization adds a leading dimension for specialization cases, as shown below. This count is independent of graph lanes and physical cores.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>specialization_count</code>: optional positive i64, default 1. Values greater than one add a body index argument and a result dimension for specialization cases.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Records source selection and constant shaping for a scheduled consumer. Here, the body forwards its complete source through <a href="#spat.yield"><code>spat.yield</code></a>. Later phases use this body to derive routing and realize the transfer. For several sources, <a href="#spat.deferred_source_select"><code>spat.deferred_source_select</code></a> records which source a specialization uses.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: at least one source; one body block; exact source argument types; specialization argument is index when count>1. The body ends in <a href="#spat.yield"><code>spat.yield</code></a> with exactly one value. Ordinary yield/output types match. Grouped output and fragment are static ranked tensors, with output shape [specialization_count]+fragmentShape and matching element types. Lowering requires statically analyzable body shaping and source selection.</dd>
|
||||
</dl>
|
||||
<p>For example, two specialization cases can select different sources. Generic assembly declares the source arguments and the case index explicitly:</p>
|
||||
<pre data-example="deferred-group"><code>%cases = "spat.deferred_communication"(%a, %b) ({
|
||||
^bb0(%a0: tensor<1x4xf32>, %b0: tensor<1x4xf32>, %case: index):
|
||||
%selected = spat.deferred_source_select %case of %a0, %b0 : tensor<1x4xf32>
|
||||
spat.yield %selected : tensor<1x4xf32>
|
||||
}) {specialization_count = 2 : i64} : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<2x1x4xf32></code></pre>
|
||||
<p>Case 0 selects <code>%a</code>, and case 1 selects <code>%b</code>. Each case yields a 1×4 fragment. The result shape 2×1×4 counts those two cases. Print this explicit form with <code>onnx-mlir-opt --maccel=PIM --mlir-print-op-generic</code>.</p>
|
||||
<p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.deferred_source_select">
|
||||
<h3><a href="#spat.deferred_source_select"><code>spat.deferred_source_select</code></a> — Select a published source</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.deferred_source_select %selector of %a, %b : tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">selector (<code>%selector</code>): an index SSA value. sources (<code>%a</code>, <code>%b</code>): the ordered, nonempty source list.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output: selected source value of the common source type.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Selects sources[selector] during compile-time communication planning. In the example, selector 0 chooses %a and selector 1 chooses %b. The enclosing <a href="#spat.deferred_communication"><code>spat.deferred_communication</code></a> or scheduled compute supplies a statically analyzable selector.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: index selector; nonempty sources; all source and output types match. Parent must be <a href="#spat.deferred_communication"><code>spat.deferred_communication</code></a>, <a href="#spat.scheduled_compute"><code>spat.scheduled_compute</code></a>, or <a href="#spat.scheduled_compute_batch"><code>spat.scheduled_compute_batch</code></a>. Producer assumption: selector is statically analyzable and in [0,sourceCount). The operation verifier does not check selector bounds.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.extract_rows">
|
||||
<h3><a href="#spat.extract_rows"><code>spat.extract_rows</code></a> — Split a matrix into row values</h3>
|
||||
<pre data-field="syntax"><code>%rows:2 = spat.extract_rows %matrix : tensor<2x4xf32> -> tensor<1x4xf32> x2</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%matrix</code>): a rank-2 matrix with shape R×C, here 2×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">outputs (<code>%rows#0</code>, <code>%rows#1</code>): R separate rank-2 tensors with shape 1×C, in row order. See <a href="#compact">multiple-result notation</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Result i contains input[i:i+1, :]. The example produces two 1×4 row values and retains the size-one row dimension.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: rank-2 input; output count equals R when R is static. Each output has rank 2, first dimension 1, matching element type, and matching C when C is static. Dynamic dimensions receive the checks that can be established statically. Lowering creates static tensor.extract_slice operations and requires static ranked tensors before <a href="#destinations">bufferization</a>. Although ODS accepts memrefs, this lowering requires tensors.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.flatten_plan">
|
||||
<h3><a href="#spat.flatten_plan"><code>spat.flatten_plan</code></a> — Plan logical flattening</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.flatten_plan"(%x) <{axis = 1 : i64, logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>) -> tensor<1x24xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): a logical tensor, here with NCHW shape 1×2×3×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>. <code>axis = 1 : i64</code> selects the division between the two dimension products.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Preserves logical element order while combining dimensions around axis. The dimensions before axis form the first output dimension; the remaining dimensions form the second. Here, axis 1 produces shape 1×24. Fragmented inputs require the reconstruction described under <a href="#input-representations">compute input representations</a>.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: static ranked tensor input, rank-2 output, matching element types, positive dimensions, and nchw layout. The normalized axis lies in [0,inputRank], and both output dimensions match their corresponding dimension products. Producers must preserve logical order through the <a href="#input-representations">input representation mapping</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.global_average_pool_plan">
|
||||
<h3><a href="#spat.global_average_pool_plan"><code>spat.global_average_pool_plan</code></a> — Plan global spatial mean</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.global_average_pool_plan"(%x) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>) -> tensor<1x2x1x1xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): an NCHW tensor, here with two channels and spatial shape 3×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Averages all H×W elements independently for each channel. The example averages 12 elements per channel and returns shape 1×2×1×1.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: static rank-4 tensors, matching element types, batch dimension 1, matching input/output channels, output H=W=1, nchw layout. Nonempty spatial domains and supported numeric element types remain producer/lowering requirements.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.graph_compute">
|
||||
<h3><a href="#spat.graph_compute"><code>spat.graph_compute</code></a> — Logical compute node</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.graph_compute [] = [] (%arg) = (%x) crossbarWeights 0 : [] (tensor<1x4xf32>) -> tensor<1x4xf32> {
|
||||
%v = spat.relu(%arg) : tensor<1x4xf32> -> tensor<1x4xf32>
|
||||
spat.yield %v : tensor<1x4xf32>
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">inputs (<code>%x</code>): runtime values bound to body arguments, here <code>%arg</code>. The empty square brackets declare no weights in this example. Weighted bindings are shown under <a href="#compute-regions">compute regions and bindings</a>. Input coordinates follow the <a href="#input-representations">producer representation</a>.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the value returned by <a href="#spat.yield"><code>spat.yield</code></a>, with the same complete type. Here, the body returns one 1×4 tensor. The scalar compute introduces no fragment-slot dimension.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>coreId</code>: optional placement ID. <code>crossbarWeights</code>: the derived count of distinct resident weights used in the body; see <a href="#compute-regions">compute regions and bindings</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Describes a graph computation before scheduling. The example applies <a href="#spat.relu"><code>spat.relu</code></a> to the bound input and returns its result through <a href="#spat.yield"><code>spat.yield</code></a>. Weight and input bindings define dataflow; memory allocation occurs later.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints"><p>Verified: a nonempty body with weight arguments followed by input arguments in each block. Argument types exactly match operand types. Terminator values match the result count and complete types, including encodings. A single-block body must use every input argument.</p><p>Weights must be compile-time computable. Nonconstant external captures require explicit input bindings, except recorded <a href="#spat.deferred_communication">deferred communication sources</a>. Direct capture of another compute result is rejected. Graph regions can contain structural blocks; scheduling must resolve their dependencies.</p><p>Target lowering and emission check hardware capacity for the selected target.</p></dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.graph_compute_batch">
|
||||
<h3><a href="#spat.graph_compute_batch"><code>spat.graph_compute_batch</code></a> — Logical batch with an SSA fragment collection</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.graph_compute_batch %lane = 0 to 2 [] = [] (%arg) = (%x) shared_outs(%out) crossbarWeights 0 : [] (tensor<1x8xf32>) -> tensor<2x1x4xf32> {
|
||||
%offset = affine.apply affine_map<(d0) -> (d0 * 4)>(%lane)
|
||||
%fragment = tensor.extract_slice %arg[0, %offset] [1, 4] [1, 1] : tensor<1x8xf32> to tensor<1x4xf32>
|
||||
%v = spat.relu(%fragment) : tensor<1x4xf32> -> tensor<1x4xf32>
|
||||
spat.in_parallel {
|
||||
tensor.parallel_insert_slice %v into %out[%lane, 0, 0] [1, 1, 4] [1, 1, 1] : tensor<1x4xf32> into tensor<2x1x4xf32>
|
||||
}
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): one logical 1×8 tensor bound as <code>%arg</code> for both lanes. The lane index is the first body argument. Each weight or input binding preserves its exact operand type. Bodies may select several slices or weight tiles and perform reductions. See <a href="#input-representations">input representations</a> for other supported coordinate forms.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): one SSA collection with two fragment slots, each containing a 1×4 tensor. In general, each result has shape [laneCount]+shape(fragment). <code>shared_outs(%out)</code> declares the corresponding body argument without an external destination operand. Resultful bodies publish through <a href="#spat.in_parallel"><code>spat.in_parallel</code></a>; resultless bodies end with an empty <a href="#spat.yield"><code>spat.yield</code></a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>laneCount</code>: positive i32 printed as the exclusive upper bound of the lane range. <code>coreIds</code>: optional dense i32 placement list with one distinct nonnegative core ID per lane. <code>crossbarWeights</code>: a derived resident-weight count. The <a href="#scheduling">scheduling example</a> distinguishes lanes and cores.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Runs the same body for each graph lane. Lane 0 applies ReLU to columns 0–3; lane 1 applies ReLU to columns 4–7. Each publishes one 1×4 fragment into the 2×1×4 result. The <a href="#graph-batches">graph batch example</a> shows how <a href="#spat.blueprint"><code>spat.blueprint</code></a> reconstructs the logical 1×8 tensor. A statically analyzable slot permutation can separate publication order from lane order. Shared SSA bindings determine dataflow; allocation and placement remain later decisions.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: positive laneCount; nonempty body; argument order is lane, weights, inputs, outputs. All resource and output argument types match their outer types exactly. Weights are compile-time computable and nonconstant captures are rejected. Optional coreIds have length laneCount, distinct nonnegative entries. Resultful blocks end in <a href="#spat.in_parallel"><code>spat.in_parallel</code></a>; resultless blocks end in <a href="#spat.yield"><code>spat.yield</code></a> with no values. Graph contract: one equal-type fragment publication per lane per result; result shape [N]+shape(F), offsets [slot,0,...], sizes [1]+shape(F), unit strides. Direct extract_slice operations require static ranked tensors, static sizes, unit strides, and supported static or lane-dependent offsets. The <a href="#graph-batches">graph fragment contract</a> defines construction and reconstruction requirements.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.host_store_sync">
|
||||
<h3><a href="#spat.host_store_sync"><code>spat.host_store_sync</code></a> — Publish through shared host memory</h3>
|
||||
<pre data-field="syntax"><code>spat.host_store_sync %x from %source to %target host_offset %offset event %event : tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the tensor payload. sourceCoreId (<code>%source</code>), targetCoreId (<code>%target</code>), hostOffset (<code>%offset</code>), and eventRegister (<code>%event</code>): index SSA operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required. The hostOffset operand gives the byte offset within the pipeline host buffer.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Stores the payload at hostOffset, then signals its availability to the consumer. Lowers to <a href="#pim.memcp_dh"><code>pim.memcp_dh</code></a> followed by <a href="#pim.sync"><code>pim.sync</code></a>. The matching <a href="#spat.host_wait_load"><code>spat.host_wait_load</code></a> waits before reading this host slot.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks index operand types; this operation has no custom verifier. Operands must resolve statically at emission. Register allocation and transfer planning must satisfy the <a href="#communication">signal/wait contract</a>. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization invariant</a> requires exact counts, separate event roles, host-slot lifetime protection, and restart ordering. These requirements prevent overshoot, register collisions, missing signals, and deadlock. Assumed: source placement is correct; the host buffer exists; the static payload fits its host slice. Before the next overwrite, the writer must receive the FREE signals for all readers.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.host_wait_load">
|
||||
<h3><a href="#spat.host_wait_load"><code>spat.host_wait_load</code></a> — Wait and read a host payload</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.host_wait_load from %source to %target host_offset %offset event %event count %count : tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">sourceCoreId (<code>%source</code>), targetCoreId (<code>%target</code>), hostOffset (<code>%offset</code>), eventRegister (<code>%event</code>), and waitValue (<code>%count</code>): index SSA operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output: payload loaded into local storage.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required. The hostOffset operand gives the byte offset within the pipeline host buffer.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Waits for the READY event from <a href="#spat.host_store_sync"><code>spat.host_store_sync</code></a>, then loads the host payload. Lowers to <a href="#pim.wait"><code>pim.wait</code></a> followed by <a href="#pim.memcp_hd"><code>pim.memcp_hd</code></a>. For repeated execution, reader-entry FREE signals protect host-slot reuse, as described in the <a href="#communication">synchronization contract</a>.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks index operand types; this operation has no custom verifier. Operands must resolve statically at emission. Register allocation and transfer planning must satisfy the <a href="#communication">signal/wait contract</a>. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization invariant</a> requires exact counts, separate event roles, host-slot lifetime protection, and restart ordering. These requirements prevent overshoot, register collisions, missing signals, and deadlock. Assumed: a matching writer uses the same host offset, complete payload type and size, and event count. The host data must remain live until the read completes.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.in_parallel">
|
||||
<h3><a href="#spat.in_parallel"><code>spat.in_parallel</code></a> — Publish lane fragments</h3>
|
||||
<pre data-field="syntax"><code>spat.in_parallel {
|
||||
tensor.parallel_insert_slice %v into %out[%lane, 0, 0] [1, 1, 4] [1, 1, 1] : tensor<1x4xf32> into tensor<2x1x4xf32>
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">The nested insertion reads <code>%v</code>, a 1×4 lane fragment, and targets <code>%out</code>, the parent batch output argument. These are operands of tensor.parallel_insert_slice; <a href="#spat.in_parallel"><code>spat.in_parallel</code></a> has no direct operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">The enclosed insertions publish into the parent batch results. This example fills one slot of a 2×1×4 graph result. See the complete <a href="#graph-batches">graph batch example</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Terminates a resultful batch body with its lane publications. The example inserts one fragment at [%lane,0,0] with size [1,1,4] and unit strides. For graph batches, these are physical publication slots. A following <a href="#spat.blueprint"><code>spat.blueprint</code></a> supplies logical placement; arithmetic reductions belong in compute operations.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: the parent is <a href="#spat.graph_compute_batch">spat.graph_compute_batch</a> or <a href="#spat.scheduled_compute_batch">spat.scheduled_compute_batch</a> with results. The region contains only tensor.parallel_insert_slice operations targeting parent output arguments. Tensors and insertion sizes are static, and strides are one. Offsets must be supported static or lane expressions. Graph publications follow the <a href="#graph-batches">fragment-slot contract</a>. Independent lanes must write disjoint destinations.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.materialize_layout">
|
||||
<h3><a href="#spat.materialize_layout"><code>spat.materialize_layout</code></a> — Convert a physical layout</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.materialize_layout"(%x) <{sourcePhysicalLayout = #spat<physical_layout dense_nchw>, targetPhysicalLayout = #spat<physical_layout nhwc_row_strip>, logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): a logical tensor in sourcePhysicalLayout. The example uses logical NCHW shape 1×2×3×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>. <code>sourcePhysicalLayout</code> and <code>targetPhysicalLayout</code> identify the source and destination storage layouts. Supported conversions are listed in the <a href="../compiler/spatial-layouts.md">layout reference</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Converts storage from sourcePhysicalLayout to targetPhysicalLayout while preserving logical values. Here, dense_nchw becomes nhwc_row_strip. The logical shape stays 1×2×3×4. This explicit conversion also forms a boundary for physical layout planning.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: ranked tensor input and output, matching element types, and known logical and physical layouts. Physical enums are dense_nchw, nchw_row_strip, nhwc_row_strip, and fragmented. Lowering must implement the selected source/target conversion and preserve logical shape. See the <a href="../compiler/spatial-layouts.md">supported conversion list</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.max_pool2d_plan">
|
||||
<h3><a href="#spat.max_pool2d_plan"><code>spat.max_pool2d_plan</code></a> — Plan 2D max pooling</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.max_pool2d_plan"(%x) <{kernelShape = array<i64: 2, 2>, pads = array<i64: 0, 0, 0, 0>, strides = array<i64: 2, 2>, dilations = array<i64: 1, 1>, logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x4x4xf32>) -> tensor<1x2x2x2xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): an NCHW tensor, here with two channels and spatial shape 4×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>. <code>kernelShape</code>: [height,width] window size in elements. <code>pads</code>: [top,left,bottom,right] in elements. <code>strides</code> and <code>dilations</code>: [height,width] element steps. The <code>array<i64: ...></code> notation stores these integer lists.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Takes the maximum over each spatial window independently within each channel. The example uses 2×2 windows with stride 2 and returns a 2×2 spatial result. Dilations determine the sample spacing within each window.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: static rank-4 tensors, matching element types and batch/channel dimensions, and nchw layout. Kernel, stride, and dilation arrays each have two entries; pads has four. Assumed: positive window parameters, correct spatial output dimensions, and padding supported by lowering. The single result contains pooled values.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.relu">
|
||||
<h3><a href="#spat.relu"><code>spat.relu</code></a> — Element-wise ReLU</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.relu(%x) : tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete computation slice, here a 1×4 tensor.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): one value per input element, here a 1×4 tensor.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = max(x[i],0). The formula applies independently to all four elements in this example.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped operand and result types; this operation has no custom verifier. Assumed: matching input/output shapes and compatible numeric element types. The <a href="#contracts">code generation requirements</a> apply to static storage and backend element types.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.relu_plan">
|
||||
<h3><a href="#spat.relu_plan"><code>spat.relu_plan</code></a> — Plan ReLU</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.relu_plan"(%x) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): a logical tensor, here with NCHW shape 1×2×3×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Applies y[i] = max(x[i],0) independently to each element. Logical coordinates and shape are preserved.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: ranked tensor input and output, matching element types, and known logical layout. Assumed: the producer preserves the element-wise shape. Shape equality is not independently checked by this verifier. The selected layout and lowering must support the shape.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.resize_nearest_plan">
|
||||
<h3><a href="#spat.resize_nearest_plan"><code>spat.resize_nearest_plan</code></a> — Plan nearest-neighbor resize</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.resize_nearest_plan"(%x) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x2x2xf32>) -> tensor<1x2x4x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): an NCHW tensor, here with two channels and spatial shape 2×2.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Uses nearest-neighbor sampling with asymmetric coordinates. The result shape supplies the target spatial sizes. The example expands each 2×2 plane to 4×4; input/output scale determines the source coordinates.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: static rank-4 tensors, matching element types, positive dimensions, and nchw layout. Assumed: batch and channel dimensions are preserved. Lowering must support the nearest-neighbor sampling and asymmetric coordinates described above.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.scheduled_compute">
|
||||
<h3><a href="#spat.scheduled_compute"><code>spat.scheduled_compute</code></a> — Placed compute node</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.scheduled_compute [] = [] (%arg) = (%x) crossbarWeights 0 : [] (tensor<1x4xf32>) -> tensor<1x4xf32> {
|
||||
%v = spat.relu(%arg) : tensor<1x4xf32> -> tensor<1x4xf32>
|
||||
spat.yield %v : tensor<1x4xf32>
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">inputs (<code>%x</code>): runtime operands bound to body arguments, here <code>%arg</code>. Square brackets bind constant weight resources when present. See <a href="#compute-regions">compute regions and bindings</a>.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the value returned by <a href="#spat.yield"><code>spat.yield</code></a>, with the same complete type. The example returns a 1×4 ReLU result.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>coreId</code>: optional placement ID. <code>crossbarWeights</code>: the derived count of distinct resident weights used in the body; see <a href="#compute-regions">compute regions and bindings</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Describes a computation after scheduling. The example applies <a href="#spat.relu"><code>spat.relu</code></a> on its assigned core. Inputs become available through local SSA forwarding or explicit <a href="#spat.channel_send"><code>spat.channel_send</code></a> and <a href="#spat.channel_receive"><code>spat.channel_receive</code></a> operations.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints"><p>Verified: a nonempty body with weight arguments followed by input arguments in each block. Argument types exactly match operand types. Terminator values match the result count and complete types, including encodings. A single-block body must use every input argument.</p><p>Weights must be compile-time computable. Nonconstant external captures require explicit input bindings, except recorded <a href="#spat.deferred_communication">deferred communication sources</a>. Direct capture of another compute result is rejected. Scheduled scalar regions require exactly one block ending in <a href="#spat.yield">spat.yield</a>.</p><p>Target lowering and emission check hardware capacity for the selected target.</p></dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.scheduled_compute_batch">
|
||||
<h3><a href="#spat.scheduled_compute_batch"><code>spat.scheduled_compute_batch</code></a> — Placed batch of equivalent computations</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.scheduled_compute_batch %lane = 0 to 2 [] = [] (%arg) = (%x) shared_outs(%out) crossbarWeights 0 : [] (tensor<2x1x4xf32>) -> tensor<2x1x4xf32> {
|
||||
%fragment = tensor.extract_slice %arg[%lane, 0, 0] [1, 1, 4] [1, 1, 1] : tensor<2x1x4xf32> to tensor<1x4xf32>
|
||||
%v = spat.relu(%fragment) : tensor<1x4xf32> -> tensor<1x4xf32>
|
||||
spat.in_parallel {
|
||||
tensor.parallel_insert_slice %v into %out[%lane, 0, 0] [1, 1, 4] [1, 1, 1] : tensor<1x4xf32> into tensor<2x1x4xf32>
|
||||
}
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): a 2×1×4 collection bound as <code>%arg</code>. Each lane extracts one 1×4 fragment in this example. Weight and input bindings preserve exact types; other input shapes follow the body accesses. See <a href="#input-representations">input representations</a>.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): one SSA result with body argument <code>%out</code>. Here, lane insertions fill a 2×1×4 result. Other result shapes follow scheduled execution and need not begin with laneCount. Resultful bodies use <a href="#spat.in_parallel"><code>spat.in_parallel</code></a>; resultless bodies use an empty <a href="#spat.yield"><code>spat.yield</code></a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>laneCount</code>: positive i32 printed as the exclusive upper bound of the lane range. <code>coreIds</code>: optional dense i32 placement list with one distinct nonnegative core ID per lane. <code>crossbarWeights</code>: a derived resident-weight count. The <a href="#scheduling">scheduling example</a> distinguishes lanes and cores.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Groups equivalent scheduled computations in one body. Here, each lane reads a fragment, applies ReLU, and publishes the updated fragment. <a href="#scheduling">Scheduled lane placement</a> determines which core executes each instance. Local forwarding and explicit communication determine input availability.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: positive laneCount; nonempty body; argument order is lane, weights, inputs, outputs. All resource and output argument types match their outer types exactly. Weights are compile-time computable and nonconstant captures are rejected. Optional coreIds have length laneCount, distinct nonnegative entries. Resultful blocks end in <a href="#spat.in_parallel"><code>spat.in_parallel</code></a>; resultless blocks end in <a href="#spat.yield"><code>spat.yield</code></a> with no values. Scheduled batches skip the graph-only extract-slice offset restriction. Spatial-to-PIM currently requires channelized, resultless scheduled batches with an empty yield.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.sigmoid">
|
||||
<h3><a href="#spat.sigmoid"><code>spat.sigmoid</code></a> — Element-wise sigmoid</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.sigmoid(%x) : tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete computation slice, here a 1×4 tensor.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): one value per input element, here a 1×4 tensor.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = 1/(1+exp(-x[i])). The formula applies independently to all four elements in this example.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped operand and result types; this operation has no custom verifier. Assumed: matching input/output shapes and compatible numeric element types. The <a href="#contracts">code generation requirements</a> apply to static storage and backend element types.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.silu_plan">
|
||||
<h3><a href="#spat.silu_plan"><code>spat.silu_plan</code></a> — Plan SiLU</h3>
|
||||
<pre data-field="syntax"><code>%y = "spat.silu_plan"(%x) <{logicalLayout = #spat<logical_layout nchw>}> : (tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): a logical tensor, here with NCHW shape 1×2×3×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the logical result with the printed shape. Physical representation is selected through <a href="#planning">layout planning</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>logicalLayout</code>: required logical coordinate order, <code>nchw</code> in the example. See <a href="#planning">planning operations and attributes</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Applies y[i] = x[i]/(1+exp(-x[i])) independently to each element. Logical coordinates and shape are preserved.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: ranked tensor input and output, matching element types, and known logical layout. Assumed: the producer preserves the element-wise shape. Shape equality is not independently checked by this verifier. The selected layout and lowering must support the shape.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.softmax">
|
||||
<h3><a href="#spat.softmax"><code>spat.softmax</code></a> — Softmax of a complete slice</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.softmax(%x) : tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete computation slice, here a 1×4 tensor.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): one value per input element, here a 1×4 tensor.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = exp(x[i])/sum_j exp(x[j]). The sum covers all four input elements in this example.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped operand and result types; this operation has no custom verifier. Assumed: identical input/output shapes and compatible numeric element types. The whole input forms one normalization domain. Producers must extract separate slices before this operation for axis-specific softmax. Numerical stability depends on the backend. Final PIM code generation requires static storage and supported element types.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.sync">
|
||||
<h3><a href="#spat.sync"><code>spat.sync</code></a> — Signal an event register</h3>
|
||||
<pre data-field="syntax"><code>spat.sync %target event %event</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">targetCoreId (<code>%target</code>): the destination core ID. eventRegister (<code>%event</code>): its local event-register index. Both are index SSA operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Increments the selected event register on the target core. Lowers to <a href="#pim.sync"><code>pim.sync</code></a>; the matching <a href="#spat.wait"><code>spat.wait</code></a> executes on that target. See the <a href="#communication">paired signal and wait examples</a>.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks index operand types; this operation has no custom verifier. Operands must resolve statically at emission. Register allocation and transfer planning must satisfy the <a href="#communication">signal/wait contract</a>. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization invariant</a> requires exact counts, separate event roles, host-slot lifetime protection, and restart ordering. These requirements prevent overshoot, register collisions, missing signals, and deadlock.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.vadd">
|
||||
<h3><a href="#spat.vadd"><code>spat.vadd</code></a> — Element-wise addition</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.vadd %a, %b : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): shaped numeric operands, each 1×4 in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the element-wise result, here with shape 1×4.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = lhs[i] + rhs[i], independently for every element in the supplied slice.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: lhs, rhs, and output have exactly the same complete type. Producers must expand any scalar or ONNX broadcast to matching shapes before this operation. Code generation requires static sizes and compatible numeric data; see <a href="#contracts">code generation requirements</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.vavg">
|
||||
<h3><a href="#spat.vavg"><code>spat.vavg</code></a> — Average a complete slice</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.vavg(%x) : tensor<1x4xf32> -> tensor<1x1xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete computation slice, here a 1×4 tensor.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): one average value in a 1×1 tensor.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[0,0] = sum(x)/number_of_elements(x). The sum covers all four input elements in this example.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped operand and result types; this operation has no custom verifier. Assumed: a nonempty input and a one-element output with compatible element type, conventionally 1×1. The operation averages the whole input slice. Final PIM code generation requires static storage and supported element types.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.vmax">
|
||||
<h3><a href="#spat.vmax"><code>spat.vmax</code></a> — Element-wise maximum</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.vmax %a, %b : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): shaped numeric operands, each 1×4 in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the element-wise result, here with shape 1×4.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = max(lhs[i], rhs[i]), independently for every element in the supplied slice.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: lhs, rhs, and output have exactly the same complete type. Producers must expand broadcasts to matching shapes before this operation. The <a href="#contracts">code generation requirements</a> apply to static sizes and numeric types.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.vmul">
|
||||
<h3><a href="#spat.vmul"><code>spat.vmul</code></a> — Element-wise multiplication</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.vmul %a, %b : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): shaped numeric operands, each 1×4 in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the element-wise result, here with shape 1×4.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = lhs[i] * rhs[i], independently for every element in the supplied slice.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks shaped operand types; this operation has no custom shape verifier. Lowering to <a href="#pim.vvmul"><code>pim.vvmul</code></a> reads both operands for the full result length. Producers must therefore supply matching shapes and expand any broadcast before this operation. Code generation requires static sizes and compatible numeric data.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.vsub">
|
||||
<h3><a href="#spat.vsub"><code>spat.vsub</code></a> — Element-wise subtraction</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.vsub %a, %b : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): shaped numeric operands, each 1×4 in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the element-wise result, here with shape 1×4.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = lhs[i] - rhs[i].</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: lhs, rhs, and output have exactly the same complete type. Producers must expand any broadcast to matching shapes before this operation.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.vvdmul">
|
||||
<h3><a href="#spat.vvdmul"><code>spat.vvdmul</code></a> — Dot product of runtime vectors</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.vvdmul %a, %b : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x1xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): rank-2 row vectors with matching shape 1×N, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): a 1×1 tensor containing the dot product.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">output[0,0] = sum_i lhs[0,i]*rhs[0,i]. Both vectors are runtime operands; no resident crossbar weight is required.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: ranked shaped types; rank 2 throughout; identical element types; lhs/rhs shapes equal 1×N with N>0; output exactly 1×1.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.wait">
|
||||
<h3><a href="#spat.wait"><code>spat.wait</code></a> — Wait for an exact event count</h3>
|
||||
<pre data-field="syntax"><code>spat.wait %event value %count</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">eventRegister (<code>%event</code>): a register on the executing core. waitValue (<code>%count</code>): the exact expected signal count. Both are index SSA operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Blocks until the local event register equals waitValue, then resets it to zero. Lowers to <a href="#pim.wait"><code>pim.wait</code></a>. The corresponding <a href="#spat.sync"><code>spat.sync</code></a> operations must supply exactly that count.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks index operand types; this operation has no custom verifier. Operands must resolve statically at emission. Register allocation and transfer planning must satisfy the <a href="#communication">signal/wait contract</a>. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization invariant</a> requires exact counts, separate event roles, host-slot lifetime protection, and restart ordering. These requirements prevent overshoot, register collisions, missing signals, and deadlock.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.wvmm">
|
||||
<h3><a href="#spat.wvmm"><code>spat.wvmm</code></a> — Row vector times explicit constant matrix</h3>
|
||||
<pre data-field="syntax"><code>%y = spat.wvmm[%weight](%x) : (tensor<4x3xf32>, tensor<1x4xf32>) -> tensor<1x3xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">weight (<code>%weight</code>): a matrix W with shape N×M, here 4×3. input (<code>%x</code>): a row vector with shape 1×N, here 1×4. The <a href="#compute-regions">weighted compute example</a> shows their region bindings.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): a row vector with shape 1×M, here 1×3.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required. The weight matrix is the explicit operand in square brackets.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Computes y[0,j] = sum_i x[0,i]*W[i,j]. In the example, each of the three output elements sums four products. A following operation can add bias or apply an activation.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: weight/input/output rank 2; N,M>0; input exactly 1×N; output exactly 1×M. Numeric type compatibility is a producer assumption. Compute parents require attached weights to be statically computable. Spatial defines logical shapes; PIM lowering selects physical array groups and padding.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="spat.yield">
|
||||
<h3><a href="#spat.yield"><code>spat.yield</code></a> — Return region values</h3>
|
||||
<pre data-field="syntax"><code>spat.yield %v : tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">outputs (<code>%v</code>): values returned by the enclosing region. The example returns one 1×4 tensor; each expanded operand has a corresponding printed type.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">The operation has no direct SSA results. Its operands become the enclosing compute or deferred-region results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Terminates the enclosing region and returns its values, as shown in the <a href="#compute-regions">compute example</a>. A resultless batch uses the empty form <code>spat.yield :</code>. A resultful batch publishes through <a href="#spat.in_parallel"><code>spat.in_parallel</code></a> instead.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Terminator trait applies. Custom parser checks operand/type counts. Scalar compute parents check exact result types and counts. Deferred communication yields exactly one payload. Resultful compute batches use <a href="#spat.in_parallel"><code>spat.in_parallel</code></a> instead.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Spatial/Spatial.td">definition</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Spatial/SpatialOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Conversion/SpatialToPim/SpatialToPim.td">arithmetic lowering</a>.</p></article>
|
||||
<article id="pim.concat">
|
||||
<h3><a href="#pim.concat"><code>pim.concat</code></a> — Concatenate into a destination</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.concat axis 1 %a, %b into %dst : (tensor<1x2xf32> x2) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">inputs (<code>%a</code>, <code>%b</code>): ordered 1×2 tensors. outputBuffer (<code>%dst</code>): the destination after <code>into</code>, with type inferred from the 1×4 result.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">axis: required i64 printed positionally; duplicate attr-dict axis is rejected.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Joins the inputs along axis into the destination. Here, axis 1 produces a 1×4 row from two 1×2 rows. Lowering uses contiguous block copies. For an inner axis with several outer coordinates, it copies one block per outer coordinate.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: at least one input and an axis in [0,outputRank). Producers must normalize negative axes before this operation. Input ranks and element types match the output. Static non-axis dimensions match. When all axis sizes are static, their sum equals the output axis size. Dynamic dimensions receive the comparisons that can be established statically. The parser checks expanded input and type counts. All values use the same tensor-or-memref container kind. Destination and result match in kind, element type, and shape; this helper does not compare layout or encoding. Code generation requires static addressable storage. Assumed: local buffers are contiguous and input/destination overlap does not destroy unread input.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.core">
|
||||
<h3><a href="#pim.core"><code>pim.core</code></a> — Execute one core stream</h3>
|
||||
<pre data-field="syntax"><code>pim.core [] = [] coreId 0 : [] -> () {
|
||||
pim.halt
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">weights: constant resources bound to body arguments in square brackets. The shown <code>[] = []</code> binding is empty. The <a href="#compute-regions">weighted compute example</a> explains the same binding convention.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results; results are communicated or written to host memory.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>coreId</code>: required i32 placement ID, printed as coreId 0 in the example. Before emission, <a href="#contracts">memory planning</a> adds pim.local_memory_size and allocation addresses.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Executes one PIM instruction stream. This example contains only <a href="#pim.halt"><code>pim.halt</code></a>. A stream with weighted arithmetic passes a bound weight operand to <a href="#pim.vmm"><code>pim.vmm</code></a>. Code generation can remap the core ID.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: one block with one exact-type argument per weight. External body references must be constants or explicit host-transfer operands. Code generation additionally requires static weights, valid local allocations and memory plans, legal host/device transfers, sufficient hardware resources, and a terminating <a href="#pim.halt"><code>pim.halt</code></a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.core_batch">
|
||||
<h3><a href="#pim.core_batch"><code>pim.core_batch</code></a> — Execute equivalent core streams</h3>
|
||||
<pre data-field="syntax"><code>pim.core_batch %lane = 0 to 2 [] = [] () = () coreIds [0, 1] : [] () -> () {
|
||||
pim.halt
|
||||
}</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">The first body argument is the index lane. Weight and input operands bind to exact-type body arguments after it; the example has empty binding lists. Lane-dependent accesses select each instance’s data. Shared SSA operands do not establish shared device-local storage or shared physical crossbars.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results; each lane executes its stream and produces memory/communication effects.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>laneCount</code>: positive i32 printed as the exclusive upper bound, here 2. <code>coreIds</code>: dense i32 placement list required by code generation, here [0,1]. See <a href="#scheduling">lane and core ranges</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Retains one common body for equivalent core streams. In the example, lane 0 executes on core 0 and lane 1 executes on core 1. Both execute <a href="#pim.halt"><code>pim.halt</code></a>. For larger bodies, lane expressions determine static addresses and peers while weight operands retain their common SSA definitions.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: one block, positive laneCount, and body arguments ordered as lane, weights, then inputs. The lane has type index, and other arguments exactly match operand types. The <a href="#pim.core">core capture rules</a> apply. Later verification requires a valid core mapping, static lane expressions, constant weight resources, and explicit local memory plans. Transfers must satisfy the <a href="#communication">communication and synchronization contract</a>. Each body ends with <a href="#pim.halt">pim.halt</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.halt">
|
||||
<h3><a href="#pim.halt"><code>pim.halt</code></a> — Stop a core stream</h3>
|
||||
<pre data-field="syntax"><code>pim.halt</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">None.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">None.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Terminates the enclosing core stream and emits the backend halt instruction. The <a href="#pim.core"><code>pim.core</code></a> and <a href="#pim.core_batch"><code>pim.core_batch</code></a> examples show its position at the end of the body.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">The terminator trait requires this operation at the end of its block. It is intended for <a href="#pim.core"><code>pim.core</code></a> and <a href="#pim.core_batch"><code>pim.core_batch</code></a> bodies; its declaration has no custom parent check.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.memcp">
|
||||
<h3><a href="#pim.memcp"><code>pim.memcp</code></a> — Copy device-local bytes</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.memcp[%dstOffset, %srcOffset](%dst, %src) {size = 16 : i32} : tensor<1x4xf32>, tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs"><code>%dst</code>: local destination. <code>%src</code>: local source. <code>%dstOffset</code> and <code>%srcOffset</code>: their respective index SSA byte offsets. The destination appears before the source.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated full destination. Its type describes the destination buffer, including bytes outside the copied range.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>size</code>: required i32 byte count, here 16. See the <a href="#memory-units">copy example and units</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Copies size bytes from %src+%srcOffset to %dst+%dstOffset. The example copies 16 bytes, enough for four f32 elements. Destination bytes outside that range retain their contents.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Source and destination are local to the executing core. This operation has no custom verifier. Later verification and emission require static nonnegative offsets and size, in-bounds memory ranges, and addressable contiguous storage. Destination and result types must match. Overlapping-copy behavior is not guaranteed; producers must avoid destructive overlap.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.memcp_dh">
|
||||
<h3><a href="#pim.memcp_dh"><code>pim.memcp_dh</code></a> — Copy device to host</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.memcp_dh[%dstOffset, %srcOffset](%dst, %src) {size = 16 : i32} : tensor<1x4xf32>, tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs"><code>%dst</code>: host destination. <code>%src</code>: local device source. <code>%dstOffset</code> and <code>%srcOffset</code>: their respective index SSA byte offsets. The destination appears before the source.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated full destination. Its type describes the destination buffer, including bytes outside the copied range.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>size</code>: required i32 byte count, here 16. See the <a href="#memory-units">copy example and units</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Copies size bytes from %src+%srcOffset to %dst+%dstOffset. The example copies 16 bytes, enough for four f32 elements. Destination bytes outside that range retain their contents.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">The destination is an explicit host operand; the source is local to the executing core. This operation has no custom verifier. Later verification and emission require static nonnegative offsets and size, in-bounds memory ranges, and addressable contiguous storage. Destination and result types must match. Overlapping-copy behavior is not guaranteed; producers must avoid destructive overlap.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.memcp_hd">
|
||||
<h3><a href="#pim.memcp_hd"><code>pim.memcp_hd</code></a> — Copy host to device</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.memcp_hd[%dstOffset, %srcOffset](%dst, %src) {size = 16 : i32} : tensor<1x4xf32>, tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs"><code>%dst</code>: local device destination. <code>%src</code>: host source. <code>%dstOffset</code> and <code>%srcOffset</code>: their respective index SSA byte offsets. The destination appears before the source.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated full destination. Its type describes the destination buffer, including bytes outside the copied range.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>size</code>: required i32 byte count, here 16. See the <a href="#memory-units">copy example and units</a>.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Copies size bytes from %src+%srcOffset to %dst+%dstOffset. The example copies 16 bytes, enough for four f32 elements. Destination bytes outside that range retain their contents.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">The destination is local to the executing core; the source is an explicit host operand. This operation has no custom verifier. Later verification and emission require static nonnegative offsets and size, in-bounds memory ranges, and addressable contiguous storage. Destination and result types must match. Overlapping-copy behavior is not guaranteed; producers must avoid destructive overlap.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.receive">
|
||||
<h3><a href="#pim.receive"><code>pim.receive</code></a> — Receive into local storage</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.receive[%offset](%dst, %source) {size = 16 : i32} : tensor<1x4xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">outputBuffer (<code>%dst</code>): local destination storage. outputOffset (<code>%offset</code>): index SSA byte offset. sourceCoreId (<code>%source</code>): index SSA ID of the sending core.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>size</code>: required i32 byte count, here 16.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Receives size bytes from the source core into %dst+%offset. The matching <a href="#pim.send"><code>pim.send</code></a> supplies the payload. See the <a href="#communication">direct-transfer example</a>.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS/interface checks only; no custom per-operation shape/bounds verifier. Later verification/emission require statically resolvable peers and offsets, valid mapped cores, nonnegative in-bounds byte ranges, contiguous local storage, and matching SEND/RECV counts/order. Receive result type must match the full destination. Incorrect transfer order can deadlock.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.send">
|
||||
<h3><a href="#pim.send"><code>pim.send</code></a> — Send local data</h3>
|
||||
<pre data-field="syntax"><code>pim.send(%x, %target) {size = 16 : i32} : tensor<1x4xf32> -> ()</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the local payload. targetCoreId (<code>%target</code>): the index SSA ID of the receiving core.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>size</code>: required i32 byte count, here 16.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Sends size bytes from the start of the input to the target core. Pair it with <a href="#pim.receive"><code>pim.receive</code></a> using the same byte count. The <a href="#communication">direct-transfer example</a> shows both sides.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS and interface checks apply; there is no custom shape or bounds verifier. Later verification and emission require a static peer ID, a valid core mapping, and an in-bounds range in contiguous local storage. The paired <a href="#pim.receive"><code>pim.receive</code></a> must use matching endpoints, byte count, and order. Incorrect transfer order can deadlock.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.sync">
|
||||
<h3><a href="#pim.sync"><code>pim.sync</code></a> — Signal an event register</h3>
|
||||
<pre data-field="syntax"><code>pim.sync %target event %event</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">targetCoreId (<code>%target</code>): the destination core ID. eventRegister (<code>%event</code>): its local event-register index. Both are index SSA operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Emits SYNC to increment the selected target-core event register. A matching <a href="#pim.wait"><code>pim.wait</code></a> consumes the expected count on that core. Synchronization-disable mode omits this instruction.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks index operand types; this operation has no custom verifier. Operands must resolve statically at emission. Register allocation and transfer planning must satisfy the <a href="#communication">signal/wait contract</a>. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization invariant</a> requires exact counts, separate event roles, host-slot lifetime protection, and restart ordering. These requirements prevent overshoot, register collisions, missing signals, and deadlock.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.transpose">
|
||||
<h3><a href="#pim.transpose"><code>pim.transpose</code></a> — Permute dimensions into a destination</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.transpose(%x, %dst) {permutation = [1, 0]} : (tensor<2x3xf32>, tensor<3x2xf32>) -> tensor<3x2xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the 2×3 source. outputBuffer (<code>%dst</code>): the 3×2 destination in the example.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the destination containing the permuted data, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>permutation</code>: required i64 array with one source dimension index per output dimension. Here, [1,0] exchanges rows and columns.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Maps output dimension d to input dimension permutation[d]. The example maps y[j,i] = x[i,j], changing shape 2×3 to 3×2. Instruction selection uses one <a href="#pim.memcp"><code>pim.memcp</code></a> for a storage-preserving case. Other permutations use static runs of <a href="#pim.memcp"><code>pim.memcp</code></a> or <a href="#pim.vmv"><code>pim.vmv</code></a> before final emission.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">The operation has no custom verifier. Before instruction selection, operands must be static memrefs. Instruction selection checks permutation length against source rank and requires every dimension exactly once, with no negative or out-of-range indices. Checked size conversions must fit backend fields. Producer assumptions: destination/result shape follows the permutation, element types match, storage is local and contiguous, and source/destination do not overlap destructively. A remaining <a href="#pim.transpose"><code>pim.transpose</code></a> is not a final executable instruction.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vavg">
|
||||
<h3><a href="#pim.vavg"><code>pim.vavg</code></a> — Average a complete vector</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vavg(%x, %dst) : (tensor<1x4xf32>, tensor<1x1xf32>) -> tensor<1x1xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete slice, here 1×4. outputBuffer (<code>%dst</code>): the destination, here 1×1.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[0,0] = sum(x)/number_of_elements(x). The example processes all four input elements and writes one average to the 1×1 destination.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">This operation has no custom shape verifier. Assumed: nonempty input and a one-element destination/result with compatible numeric type. The result refers to the destination storage. Code generation derives the processed element count from the input and requires static contiguous device-local buffers. <a href="#memory-units">Element counts and bitwidths</a> determine instruction lengths. The <a href="#contracts">code generation requirements</a> specify storage and backend limits.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vmm">
|
||||
<h3><a href="#pim.vmm"><code>pim.vmm</code></a> — Multiply using a resident array group</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vmm[%weight](%x, %dst) : (tensor<4x3xf32>, tensor<1x4xf32>, tensor<1x3xf32>) -> tensor<1x3xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">weight (<code>%weight</code>): a resident matrix resource, here 4×3. input (<code>%x</code>): a positive-width rank-2 row vector, here 1×4. outputBuffer (<code>%dst</code>): a 1×3 destination.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, with width equal to the matrix column count.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required. The square-bracket operand selects the resident weight resource.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Computes a row-vector/matrix product using a resident array group. The example maps a 1×4 row and 4×3 matrix to a 1×3 row. Weight planning maps the logical matrix to physical crossbars and supplies required padding. The vector widths follow that resource plan rather than a fixed --crossbar-size shape.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: destination/result have equal container kind, element type and shape; weight/input/output rank 2; positive weight dimensions; input 1×positiveWidth; output 1×M for weight N×M. The verifier does not enforce inputWidth=N or one-crossbar capacity. Resource planning, input padding, matching numeric types, constant weight provenance, and legal physical array-group dimensions are later-stage contracts. Buffers must be local and addressable.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vmv">
|
||||
<h3><a href="#pim.vmv"><code>pim.vmv</code></a> — Gather a strided local vector</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vmv[%dstOffset, %srcOffset, %stride](%dst, %src) {length = 4 : i32} : tensor<1x4xf32>, tensor<1x8xf32> -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">target (<code>%dst</code>): contiguous destination. source (<code>%src</code>): source storage. <code>%dstOffset</code> and <code>%srcOffset</code>: index SSA byte offsets. <code>%stride</code>: index SSA stride measured in source elements.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated full destination.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes"><code>length</code>: required positive i32 element count, here 4. The <a href="#memory-units">strided-copy example</a> shows how element stride relates to byte offsets.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">For each i in [0,length), reads one element at source+sourceOffset+i*sourceStride*elementBytes and writes the next contiguous destination element. With stride 2 and f32 data, the example selects four elements at eight-byte intervals.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">Verified: positive length; target/result match container kind, element type, and shape. Source/target use the same container kind and element type. Later verification/emission require static, nonnegative offsets/stride, valid element bitwidth and in-bounds source/destination ranges. Stride counts source elements; for f32, stride 2 selects every second element, advancing 8 bytes. Arbitrary overlapping gather/copy behavior is not guaranteed.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vrelu">
|
||||
<h3><a href="#pim.vrelu"><code>pim.vrelu</code></a> — Element-wise ReLU</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vrelu(%x, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete slice, here 1×4. outputBuffer (<code>%dst</code>): the destination, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = max(x[i],0). The example processes all four input elements and writes four values to the 1×4 destination.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">This operation has no custom shape verifier. Assumed: matching input, destination, and result shapes with compatible numeric types. The result refers to the destination storage. Code generation derives the processed element count from the input and requires static contiguous device-local buffers. <a href="#memory-units">Element counts and bitwidths</a> determine instruction lengths. The <a href="#contracts">code generation requirements</a> specify storage and backend limits.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vsigm">
|
||||
<h3><a href="#pim.vsigm"><code>pim.vsigm</code></a> — Element-wise sigmoid</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vsigm(%x, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete slice, here 1×4. outputBuffer (<code>%dst</code>): the destination, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = 1/(1+exp(-x[i])). The example processes all four input elements and writes four values to the 1×4 destination.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">This operation has no custom shape verifier. Assumed: matching input, destination, and result shapes with compatible numeric types. The result refers to the destination storage. Code generation derives the processed element count from the input and requires static contiguous device-local buffers. <a href="#memory-units">Element counts and bitwidths</a> determine instruction lengths. The <a href="#contracts">code generation requirements</a> specify storage and backend limits.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vsoftmax">
|
||||
<h3><a href="#pim.vsoftmax"><code>pim.vsoftmax</code></a> — Softmax of a complete vector</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vsoftmax(%x, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete slice, here 1×4. outputBuffer (<code>%dst</code>): the destination, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = exp(x[i])/sum_j exp(x[j]). The example processes all four input elements and writes four values to the 1×4 destination. The whole input is one normalization domain. Producers must extract separate slices for axis-specific softmax. Numerical stability depends on the executing backend.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">This operation has no custom shape verifier. Assumed: matching input, destination, and result shapes with compatible numeric types. The result refers to the destination storage. Code generation derives the processed element count from the input and requires static contiguous device-local buffers. <a href="#memory-units">Element counts and bitwidths</a> determine instruction lengths. The <a href="#contracts">code generation requirements</a> specify storage and backend limits.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vtanh">
|
||||
<h3><a href="#pim.vtanh"><code>pim.vtanh</code></a> — Element-wise hyperbolic tangent</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vtanh(%x, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">input (<code>%x</code>): the complete slice, here 1×4. outputBuffer (<code>%dst</code>): the destination, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, following the <a href="#destinations">PIM destination contract</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = tanh(x[i]). The example processes all four input elements and writes four values to the 1×4 destination.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">This operation has no custom shape verifier. Assumed: matching input, destination, and result shapes with compatible numeric types. The result refers to the destination storage. Code generation derives the processed element count from the input and requires static contiguous device-local buffers. <a href="#memory-units">Element counts and bitwidths</a> determine instruction lengths. The <a href="#contracts">code generation requirements</a> specify storage and backend limits.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vvadd">
|
||||
<h3><a href="#pim.vvadd"><code>pim.vvadd</code></a> — Element-wise addition</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vvadd(%a, %b, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): matching numeric slices, here 1×4. outputBuffer (<code>%dst</code>): the third operand, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, containing one value per input element. See <a href="#destinations">PIM destinations</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = lhs[i]+rhs[i]. Code generation uses the lhs element count to read both inputs. The example reads four elements from each input and writes four output elements.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS and destination-interface checks apply; this operation has no custom shape verifier. Assumed: matching lhs/rhs shapes and compatible numeric types. Destination and result types must match and provide the complete result shape. Producers must expand broadcasts before this operation because both inputs are read for the full lhs length. Code generation requires static contiguous device-local storage. See <a href="#memory-units">instruction units</a> and <a href="#contracts">backend requirements</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vvdmul">
|
||||
<h3><a href="#pim.vvdmul"><code>pim.vvdmul</code></a> — Dot product</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vvdmul(%a, %b, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>, tensor<1x1xf32>) -> tensor<1x1xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): matching numeric slices, here 1×4. outputBuffer (<code>%dst</code>): the third operand, here 1×1.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, containing one dot-product value. See <a href="#destinations">PIM destinations</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[0,0] = sum_i lhs[i]*rhs[i]. Code generation uses the lhs element count to read both inputs. The example reads four elements from each input and writes one dot product.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS and destination-interface checks apply; this operation has no custom shape verifier. Assumed: matching lhs/rhs shapes and compatible numeric types. Destination and result types must match and provide one element. Producers must expand broadcasts before this operation because both inputs are read for the full lhs length. Code generation requires static contiguous device-local storage. See <a href="#memory-units">instruction units</a> and <a href="#contracts">backend requirements</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vvmax">
|
||||
<h3><a href="#pim.vvmax"><code>pim.vvmax</code></a> — Element-wise maximum</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vvmax(%a, %b, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): matching numeric slices, here 1×4. outputBuffer (<code>%dst</code>): the third operand, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, containing one value per input element. See <a href="#destinations">PIM destinations</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = max(lhs[i],rhs[i]). Code generation uses the lhs element count to read both inputs. The example reads four elements from each input and writes four output elements.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS and destination-interface checks apply; this operation has no custom shape verifier. Assumed: matching lhs/rhs shapes and compatible numeric types. Destination and result types must match and provide the complete result shape. Producers must expand broadcasts before this operation because both inputs are read for the full lhs length. Code generation requires static contiguous device-local storage. See <a href="#memory-units">instruction units</a> and <a href="#contracts">backend requirements</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vvmul">
|
||||
<h3><a href="#pim.vvmul"><code>pim.vvmul</code></a> — Element-wise multiplication</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vvmul(%a, %b, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): matching numeric slices, here 1×4. outputBuffer (<code>%dst</code>): the third operand, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, containing one value per input element. See <a href="#destinations">PIM destinations</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = lhs[i]*rhs[i]. Code generation uses the lhs element count to read both inputs. The example reads four elements from each input and writes four output elements.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS and destination-interface checks apply; this operation has no custom shape verifier. Assumed: matching lhs/rhs shapes and compatible numeric types. Destination and result types must match and provide the complete result shape. Producers must expand broadcasts before this operation because both inputs are read for the full lhs length. Code generation requires static contiguous device-local storage. See <a href="#memory-units">instruction units</a> and <a href="#contracts">backend requirements</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.vvsub">
|
||||
<h3><a href="#pim.vvsub"><code>pim.vvsub</code></a> — Element-wise subtraction</h3>
|
||||
<pre data-field="syntax"><code>%y = pim.vvsub(%a, %b, %dst) : (tensor<1x4xf32>, tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32></code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">lhs (<code>%a</code>) and rhs (<code>%b</code>): matching numeric slices, here 1×4. outputBuffer (<code>%dst</code>): the third operand, here 1×4.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">output (<code>%y</code>): the updated destination, containing one value per input element. See <a href="#destinations">PIM destinations</a>.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">y[i] = lhs[i]-rhs[i]. Code generation uses the lhs element count to read both inputs. The example reads four elements from each input and writes four output elements.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS and destination-interface checks apply; this operation has no custom shape verifier. Assumed: matching lhs/rhs shapes and compatible numeric types. Destination and result types must match and provide the complete result shape. Producers must expand broadcasts before this operation because both inputs are read for the full lhs length. Code generation requires static contiguous device-local storage. See <a href="#memory-units">instruction units</a> and <a href="#contracts">backend requirements</a>.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
<article id="pim.wait">
|
||||
<h3><a href="#pim.wait"><code>pim.wait</code></a> — Wait for an exact event count</h3>
|
||||
<pre data-field="syntax"><code>pim.wait %event value %count</code></pre><dl>
|
||||
<dt>Inputs</dt><dd data-field="inputs">eventRegister (<code>%event</code>): a register on the executing core. waitValue (<code>%count</code>): the exact expected signal count. Both are index SSA operands.</dd>
|
||||
<dt>Outputs</dt><dd data-field="outputs">No SSA results.</dd>
|
||||
<dt>Attributes</dt><dd data-field="attributes">None required.</dd>
|
||||
<dt>Semantics</dt><dd data-field="semantics">Emits WAIT, which blocks until the local register equals waitValue and then resets it to zero. Matching <a href="#pim.sync"><code>pim.sync</code></a> operations supply the count. Emission omits zero-count waits and omits all waits in synchronization-disable mode.</dd>
|
||||
<dt>Constraints</dt><dd data-field="constraints">ODS checks index operand types; this operation has no custom verifier. Operands must resolve statically at emission. Register allocation and transfer planning must satisfy the <a href="#communication">signal/wait contract</a>. The <a href="../../.agents/invariants/PIM_SYNCHRONIZATION_INVARIANT.md">synchronization invariant</a> requires exact counts, separate event roles, host-slot lifetime protection, and restart ordering. These requirements prevent overshoot, register collisions, missing signals, and deadlock.</dd>
|
||||
</dl><p class="sources">Sources: <a href="../../src/PIM/Dialect/Pim/Pim.td">definition</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsAsm.cpp">assembly</a>, <a href="../../src/PIM/Dialect/Pim/PimOpsVerify.cpp">verifiers</a>, <a href="../../src/PIM/Compiler/PimCodeGen.cpp">emission</a>.</p></article>
|
||||
</section><footer>
|
||||
<p>Shared implementation sources: <a href="../../src/PIM/Common/IR/CompactAsmUtils.hpp">compact assembly</a>, <a href="../../src/PIM/Dialect/Pim/Passes/Transforms/Bufferization/OpBufferizationInterfaces.cpp">bufferization</a>, <a href="../../src/PIM/Dialect/Pim/Passes/Transforms/InstructionSelection/InstructionSelectionPass.cpp">instruction selection</a>, <a href="../../src/PIM/Dialect/Pim/Passes/Transforms/Verification/VerificationPass.cpp">PIM verification</a>, <a href="../../src/PIM/Conversion/SpatialToPim/Patterns/ChannelLowering.cpp">communication lowering</a>, <a href="../../src/PIM/Compiler/PimCoreProgram.cpp">core programs</a>.</p></footer></main>
|
||||
<script>
|
||||
const search = document.getElementById('search');
|
||||
const entries = [...document.querySelectorAll('article')];
|
||||
const links = [...document.querySelectorAll('#operation-index li')];
|
||||
search.disabled = false;
|
||||
search.addEventListener('input', () => {
|
||||
const query = search.value.trim().toLowerCase();
|
||||
const visible = new Set();
|
||||
for (const entry of entries) {
|
||||
entry.hidden = !entry.textContent.toLowerCase().includes(query);
|
||||
if (!entry.hidden) visible.add(entry.id);
|
||||
}
|
||||
for (const link of links) link.hidden = !visible.has(link.querySelector('a').hash.slice(1));
|
||||
document.getElementById('count').textContent = `${visible.size} of ${entries.length} operations`;
|
||||
});
|
||||
// A shared deep link stays usable even if an active search hid its target.
|
||||
window.addEventListener('hashchange', () => {
|
||||
const target = document.getElementById(location.hash.slice(1));
|
||||
if (target && target.hidden) {
|
||||
search.value = '';
|
||||
search.dispatchEvent(new Event('input'));
|
||||
target.scrollIntoView();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body></html>
|
||||
@@ -1,738 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="180" height="960" viewBox="0 0 180 960">
|
||||
<title>Illuminated manuscript foliage border</title>
|
||||
<desc>Procedural gold scrollwork, acanthus leaves, raptor medallions, rosettes, and pearl ornament on deep green.</desc>
|
||||
<defs>
|
||||
<linearGradient id="gold" x2="1" y2=".4">
|
||||
<stop stop-color="#80602e"/><stop offset=".35" stop-color="#ead19a"/>
|
||||
<stop offset=".6" stop-color="#b38a46"/><stop offset="1" stop-color="#e2bf73"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="jade" x2="1" y2="1">
|
||||
<stop stop-color="#749281"/><stop offset=".45" stop-color="#365d50"/><stop offset="1" stop-color="#152d27"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="red" x2="1" y2="1">
|
||||
<stop stop-color="#b86e60"/><stop offset=".5" stop-color="#793c39"/><stop offset="1" stop-color="#3e2527"/>
|
||||
</linearGradient>
|
||||
<g id="leaf" stroke="#c6a45f" stroke-width=".65" stroke-linejoin="round">
|
||||
<path fill="url(#jade)" d="M0 0C-3-8-16-7-16-19Q-11-15-8-18C-17-24-14-34-12-38Q-8-29-4-31C-10-40-3-49 1-54C0-41 11-37 7-29Q14-32 15-39C23-26 15-21 10-18Q16-17 20-22C22-9 9-10 0 0Z"/>
|
||||
<path d="M0-2Q-4-23 1-48M-2-12Q-11-14-13-20M-3-24Q-9-25-11-32M-2-34 0-41M-2-10Q11-11 16-17M-3-21Q9-22 13-31" fill="none"/>
|
||||
<path d="M-5-13Q-9-17-9-19M1-27Q4-31 3-35" fill="none" stroke="#e6d2a0" stroke-width=".45"/>
|
||||
</g>
|
||||
<g id="bud" stroke="#c6a45f" stroke-width=".65">
|
||||
<path d="M0 0Q-14-10-7-23Q-2-22 0-17Q2-22 7-23Q14-10 0 0Z" fill="url(#red)"/>
|
||||
<path d="M0 0Q-5-13 0-27Q5-13 0 0Z" fill="url(#gold)"/>
|
||||
<path d="M-6-6 0 0 6-6" fill="none"/>
|
||||
</g>
|
||||
<g id="raptor" stroke="#c6a45f" stroke-linejoin="round">
|
||||
<circle r="46" fill="#090f0c" stroke-width="1.5"/>
|
||||
<circle r="42" fill="#14221c" stroke-width=".5"/>
|
||||
<circle r="39" fill="none" stroke-width=".5" stroke-dasharray="1 3"/>
|
||||
<path d="M-26 29Q-15 12-24-1L-32-5-25-9-32-15-22-16-27-24-15-21-16-30-5-23Q7-26 17-15L34-9Q39-6 34 0L14 4 31 9Q33 13 26 16L6 12Q-2 17 0 31Z" fill="url(#jade)" stroke-width="1.2"/>
|
||||
<path d="M-26 29Q-3 25-5 6Q-16-1-12-12Q-8-21 4-18M-15 28Q3 24 3 12M-22-15-13-10M-22-6-14-4M-17 3-10 5" fill="none" stroke-width=".65"/>
|
||||
<path d="M-4-10Q3-18 12-10L5-5Z" fill="url(#gold)" stroke-width=".5"/>
|
||||
<path d="M5-13 4-7" fill="none" stroke="#090f0c" stroke-width="2"/>
|
||||
<path d="M13 4 17 8 19 3M23 2 25 6 28 1M12 13 15 9 18 14M23 15 25 11 28 14" fill="#ead7a5" stroke-width=".35"/>
|
||||
<path d="M14-4Q25-7 31-4M5 1 10 2M-10 12-7 14M-13 19-10 21" fill="none" stroke-width=".55"/>
|
||||
<circle cx="30" cy="-6" r="1.1" fill="#090f0c" stroke="none"/>
|
||||
<path d="M-5-36 0-41 5-36 0-32ZM-5 36 0 41 5 36 0 32Z" fill="url(#red)" stroke-width=".65"/>
|
||||
</g>
|
||||
</defs>
|
||||
<g stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M0 0H24V960H0Z" fill="#14221c"/>
|
||||
<path d="M3 0V960M21 0V960" stroke="url(#gold)" stroke-width="1.4"/>
|
||||
<path d="M6 0V960M18 0V960" stroke="#79633c" stroke-width=".4"/>
|
||||
|
||||
<path d="M12 -33 16 -24 12 -15 8 -24Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="-24.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 -9 16 0 12 9 8 0Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="0.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 15 16 24 12 33 8 24Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="24.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 39 16 48 12 57 8 48Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="48.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 63 16 72 12 81 8 72Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="72.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 87 16 96 12 105 8 96Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="96.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 111 16 120 12 129 8 120Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="120.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 135 16 144 12 153 8 144Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="144.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 159 16 168 12 177 8 168Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="168.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 183 16 192 12 201 8 192Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="192.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 207 16 216 12 225 8 216Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="216.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 231 16 240 12 249 8 240Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="240.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 255 16 264 12 273 8 264Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="264.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 279 16 288 12 297 8 288Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="288.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 303 16 312 12 321 8 312Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="312.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 327 16 336 12 345 8 336Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="336.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 351 16 360 12 369 8 360Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="360.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 375 16 384 12 393 8 384Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="384.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 399 16 408 12 417 8 408Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="408.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 423 16 432 12 441 8 432Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="432.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 447 16 456 12 465 8 456Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="456.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 471 16 480 12 489 8 480Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="480.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 495 16 504 12 513 8 504Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="504.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 519 16 528 12 537 8 528Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="528.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 543 16 552 12 561 8 552Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="552.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 567 16 576 12 585 8 576Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="576.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 591 16 600 12 609 8 600Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="600.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 615 16 624 12 633 8 624Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="624.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 639 16 648 12 657 8 648Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="648.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 663 16 672 12 681 8 672Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="672.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 687 16 696 12 705 8 696Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="696.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 711 16 720 12 729 8 720Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="720.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 735 16 744 12 753 8 744Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="744.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 759 16 768 12 777 8 768Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="768.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 783 16 792 12 801 8 792Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="792.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 807 16 816 12 825 8 816Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="816.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 831 16 840 12 849 8 840Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="840.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 855 16 864 12 873 8 864Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="864.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 879 16 888 12 897 8 888Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="888.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 903 16 912 12 921 8 912Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="912.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 927 16 936 12 945 8 936Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="936.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 951 16 960 12 969 8 960Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="960.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M12 975 16 984 12 993 8 984Z" fill="none" stroke="#c6a45f" stroke-width="0.5"/>
|
||||
<circle cx="12.00" cy="984.00" r="1.2" fill="#dec58e"/>
|
||||
<path d="M88 -240C150 -180 26 -60 88 0" fill="none" stroke="#594525" stroke-width="5"/>
|
||||
<path d="M88 -240C150 -180 26 -60 88 0" fill="none" stroke="url(#gold)" stroke-width="3"/>
|
||||
<path d="M88 -240C150 -180 26 -60 88 0" fill="none" stroke="#f0dab0" stroke-width="0.55"/>
|
||||
<path d="M108.00 -221.00L111.84 -220.39L115.58 -219.45L119.18 -218.20L122.62 -216.64L125.88 -214.80L128.92 -212.70L131.74 -210.35L134.30 -207.80L136.61 -205.05L138.63 -202.14L140.37 -199.09L141.81 -195.93L142.95 -192.70L143.78 -189.41L144.32 -186.10L144.54 -182.79L144.48 -179.51L144.12 -176.29L143.48 -173.15L142.57 -170.12L141.41 -167.22L140.01 -164.47L138.39 -161.89L136.56 -159.50L134.56 -157.30L132.39 -155.33L130.08 -153.58L127.66 -152.07L125.14 -150.80L122.55 -149.77L119.92 -149.00L117.27 -148.47L114.62 -148.19L111.99 -148.15L109.41 -148.35L106.89 -148.77L104.46 -149.41L102.13 -150.26L99.93 -151.30L97.86 -152.52L95.94 -153.90L94.18 -155.42L92.60 -157.07L91.20 -158.83L89.99 -160.67L88.96 -162.59L88.14 -164.56L87.51 -166.56L87.07 -168.57L86.83 -170.58L86.77 -172.56L86.90 -174.50L87.20 -176.39L87.66 -178.20L88.28 -179.93L89.04 -181.55L89.93 -183.07L90.94 -184.46L92.04 -185.73L93.24 -186.86L94.51 -187.85L95.84 -188.70L97.20 -189.39L98.60 -189.94L100.00 -190.35L101.40 -190.61L102.78 -190.73L104.13 -190.71L105.44 -190.57L106.69 -190.31L107.87 -189.94L108.98 -189.46L110.00 -188.89L110.94 -188.25L111.77 -187.53L112.50 -186.76L113.13 -185.95L113.65 -185.10L114.06 -184.24L114.36 -183.36L114.57 -182.50L114.67 -181.65L114.67 -180.82L114.58 -180.04L114.41 -179.30L114.17 -178.61L113.85 -177.99L113.48 -177.43L113.06 -176.95L112.60 -176.55L112.11 -176.22L111.61 -175.98L111.10 -175.82L110.59 -175.75L110.09 -175.75L109.62 -175.82" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M108.00 -221.00L111.84 -220.39L115.58 -219.45L119.18 -218.20L122.62 -216.64L125.88 -214.80L128.92 -212.70L131.74 -210.35L134.30 -207.80L136.61 -205.05L138.63 -202.14L140.37 -199.09L141.81 -195.93L142.95 -192.70L143.78 -189.41L144.32 -186.10L144.54 -182.79L144.48 -179.51L144.12 -176.29L143.48 -173.15L142.57 -170.12L141.41 -167.22L140.01 -164.47L138.39 -161.89L136.56 -159.50L134.56 -157.30L132.39 -155.33L130.08 -153.58L127.66 -152.07L125.14 -150.80L122.55 -149.77L119.92 -149.00L117.27 -148.47L114.62 -148.19L111.99 -148.15L109.41 -148.35L106.89 -148.77L104.46 -149.41L102.13 -150.26L99.93 -151.30L97.86 -152.52L95.94 -153.90L94.18 -155.42L92.60 -157.07L91.20 -158.83L89.99 -160.67L88.96 -162.59L88.14 -164.56L87.51 -166.56L87.07 -168.57L86.83 -170.58L86.77 -172.56L86.90 -174.50L87.20 -176.39L87.66 -178.20L88.28 -179.93L89.04 -181.55L89.93 -183.07L90.94 -184.46L92.04 -185.73L93.24 -186.86L94.51 -187.85L95.84 -188.70L97.20 -189.39L98.60 -189.94L100.00 -190.35L101.40 -190.61L102.78 -190.73L104.13 -190.71L105.44 -190.57L106.69 -190.31L107.87 -189.94L108.98 -189.46L110.00 -188.89L110.94 -188.25L111.77 -187.53L112.50 -186.76L113.13 -185.95L113.65 -185.10L114.06 -184.24L114.36 -183.36L114.57 -182.50L114.67 -181.65L114.67 -180.82L114.58 -180.04L114.41 -179.30L114.17 -178.61L113.85 -177.99L113.48 -177.43L113.06 -176.95L112.60 -176.55L112.11 -176.22L111.61 -175.98L111.10 -175.82L110.59 -175.75L110.09 -175.75L109.62 -175.82" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(134.30 -207.80) rotate(195.03) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(140.01 -164.47) rotate(267.15) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(106.89 -148.77) rotate(-20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(86.83 -170.58) rotate(53.38) scale(0.48)"/>
|
||||
<circle cx="109.62" cy="-175.82" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="109.62" cy="-175.82" r="1.5" fill="#e4c783"/>
|
||||
<path d="M68.00 -101.00L64.16 -100.39L60.42 -99.45L56.82 -98.20L53.38 -96.64L50.12 -94.80L47.08 -92.70L44.26 -90.35L41.70 -87.80L39.39 -85.05L37.37 -82.14L35.63 -79.09L34.19 -75.93L33.05 -72.70L32.22 -69.41L31.68 -66.10L31.46 -62.79L31.52 -59.51L31.88 -56.29L32.52 -53.15L33.43 -50.12L34.59 -47.22L35.99 -44.47L37.61 -41.89L39.44 -39.50L41.44 -37.30L43.61 -35.33L45.92 -33.58L48.34 -32.07L50.86 -30.80L53.45 -29.77L56.08 -29.00L58.73 -28.47L61.38 -28.19L64.01 -28.15L66.59 -28.35L69.11 -28.77L71.54 -29.41L73.87 -30.26L76.07 -31.30L78.14 -32.52L80.06 -33.90L81.82 -35.42L83.40 -37.07L84.80 -38.83L86.01 -40.67L87.04 -42.59L87.86 -44.56L88.49 -46.56L88.93 -48.57L89.17 -50.58L89.23 -52.56L89.10 -54.50L88.80 -56.39L88.34 -58.20L87.72 -59.93L86.96 -61.55L86.07 -63.07L85.06 -64.46L83.96 -65.73L82.76 -66.86L81.49 -67.85L80.16 -68.70L78.80 -69.39L77.40 -69.94L76.00 -70.35L74.60 -70.61L73.22 -70.73L71.87 -70.71L70.56 -70.57L69.31 -70.31L68.13 -69.94L67.02 -69.46L66.00 -68.89L65.06 -68.25L64.23 -67.53L63.50 -66.76L62.87 -65.95L62.35 -65.10L61.94 -64.24L61.64 -63.36L61.43 -62.50L61.33 -61.65L61.33 -60.82L61.42 -60.04L61.59 -59.30L61.83 -58.61L62.15 -57.99L62.52 -57.43L62.94 -56.95L63.40 -56.55L63.89 -56.22L64.39 -55.98L64.90 -55.82L65.41 -55.75L65.91 -55.75L66.38 -55.82" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M68.00 -101.00L64.16 -100.39L60.42 -99.45L56.82 -98.20L53.38 -96.64L50.12 -94.80L47.08 -92.70L44.26 -90.35L41.70 -87.80L39.39 -85.05L37.37 -82.14L35.63 -79.09L34.19 -75.93L33.05 -72.70L32.22 -69.41L31.68 -66.10L31.46 -62.79L31.52 -59.51L31.88 -56.29L32.52 -53.15L33.43 -50.12L34.59 -47.22L35.99 -44.47L37.61 -41.89L39.44 -39.50L41.44 -37.30L43.61 -35.33L45.92 -33.58L48.34 -32.07L50.86 -30.80L53.45 -29.77L56.08 -29.00L58.73 -28.47L61.38 -28.19L64.01 -28.15L66.59 -28.35L69.11 -28.77L71.54 -29.41L73.87 -30.26L76.07 -31.30L78.14 -32.52L80.06 -33.90L81.82 -35.42L83.40 -37.07L84.80 -38.83L86.01 -40.67L87.04 -42.59L87.86 -44.56L88.49 -46.56L88.93 -48.57L89.17 -50.58L89.23 -52.56L89.10 -54.50L88.80 -56.39L88.34 -58.20L87.72 -59.93L86.96 -61.55L86.07 -63.07L85.06 -64.46L83.96 -65.73L82.76 -66.86L81.49 -67.85L80.16 -68.70L78.80 -69.39L77.40 -69.94L76.00 -70.35L74.60 -70.61L73.22 -70.73L71.87 -70.71L70.56 -70.57L69.31 -70.31L68.13 -69.94L67.02 -69.46L66.00 -68.89L65.06 -68.25L64.23 -67.53L63.50 -66.76L62.87 -65.95L62.35 -65.10L61.94 -64.24L61.64 -63.36L61.43 -62.50L61.33 -61.65L61.33 -60.82L61.42 -60.04L61.59 -59.30L61.83 -58.61L62.15 -57.99L62.52 -57.43L62.94 -56.95L63.40 -56.55L63.89 -56.22L64.39 -55.98L64.90 -55.82L65.41 -55.75L65.91 -55.75L66.38 -55.82" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(41.70 -87.80) rotate(164.97) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(35.99 -44.47) rotate(92.85) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(69.11 -28.77) rotate(20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(89.17 -50.58) rotate(-53.38) scale(0.48)"/>
|
||||
<circle cx="66.38" cy="-55.82" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="66.38" cy="-55.82" r="1.5" fill="#e4c783"/>
|
||||
<use href="#leaf" transform="translate(95.32 -224.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M95.32 -224Q56.32 -218 56.32 -244" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(56.32 -244.00) rotate(-25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(93.56 -132.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M93.56 -132Q132.56 -126 132.56 -152" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(132.56 -152.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(80.68 -104.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M80.68 -104Q119.68 -98 119.68 -124" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(119.68 -124.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(82.44 -12.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M82.44 -12Q43.44 -6 43.44 -32" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(43.44 -32.00) rotate(-25.00) scale(0.55)"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(0)"/>
|
||||
<circle cx="58.00" cy="-149.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(45)"/>
|
||||
<circle cx="54.19" cy="-139.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(90)"/>
|
||||
<circle cx="45.00" cy="-136.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(135)"/>
|
||||
<circle cx="35.81" cy="-139.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(180)"/>
|
||||
<circle cx="32.00" cy="-149.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(225)"/>
|
||||
<circle cx="35.81" cy="-158.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(270)"/>
|
||||
<circle cx="45.00" cy="-162.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 -149) rotate(315)"/>
|
||||
<circle cx="54.19" cy="-158.19" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="45.00" cy="-149.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="45.00" cy="-149.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M42 -134q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M48 -134q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(0)"/>
|
||||
<circle cx="152.00" cy="-29.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(45)"/>
|
||||
<circle cx="148.19" cy="-19.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(90)"/>
|
||||
<circle cx="139.00" cy="-16.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(135)"/>
|
||||
<circle cx="129.81" cy="-19.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(180)"/>
|
||||
<circle cx="126.00" cy="-29.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(225)"/>
|
||||
<circle cx="129.81" cy="-38.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(270)"/>
|
||||
<circle cx="139.00" cy="-42.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 -29) rotate(315)"/>
|
||||
<circle cx="148.19" cy="-38.19" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="139.00" cy="-29.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="139.00" cy="-29.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M136 -14q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M142 -14q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<circle cx="158.00" cy="-240.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="-230.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="-220.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="-210.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="-200.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="-190.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="-180.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="-170.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="-160.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="-150.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="-140.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="-130.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="-120.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="-110.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="-100.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="-90.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="-80.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="-70.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="-60.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="-50.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="-40.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="-30.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="-20.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="-10.00" r="0.7" fill="#a58951"/>
|
||||
<path d="M151 -225V-215M147 -220H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M151 -105V-95M147 -100H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M88 0C150 60 26 180 88 240" fill="none" stroke="#594525" stroke-width="5"/>
|
||||
<path d="M88 0C150 60 26 180 88 240" fill="none" stroke="url(#gold)" stroke-width="3"/>
|
||||
<path d="M88 0C150 60 26 180 88 240" fill="none" stroke="#f0dab0" stroke-width="0.55"/>
|
||||
<path d="M108.00 19.00L111.84 19.61L115.58 20.55L119.18 21.80L122.62 23.36L125.88 25.20L128.92 27.30L131.74 29.65L134.30 32.20L136.61 34.95L138.63 37.86L140.37 40.91L141.81 44.07L142.95 47.30L143.78 50.59L144.32 53.90L144.54 57.21L144.48 60.49L144.12 63.71L143.48 66.85L142.57 69.88L141.41 72.78L140.01 75.53L138.39 78.11L136.56 80.50L134.56 82.70L132.39 84.67L130.08 86.42L127.66 87.93L125.14 89.20L122.55 90.23L119.92 91.00L117.27 91.53L114.62 91.81L111.99 91.85L109.41 91.65L106.89 91.23L104.46 90.59L102.13 89.74L99.93 88.70L97.86 87.48L95.94 86.10L94.18 84.58L92.60 82.93L91.20 81.17L89.99 79.33L88.96 77.41L88.14 75.44L87.51 73.44L87.07 71.43L86.83 69.42L86.77 67.44L86.90 65.50L87.20 63.61L87.66 61.80L88.28 60.07L89.04 58.45L89.93 56.93L90.94 55.54L92.04 54.27L93.24 53.14L94.51 52.15L95.84 51.30L97.20 50.61L98.60 50.06L100.00 49.65L101.40 49.39L102.78 49.27L104.13 49.29L105.44 49.43L106.69 49.69L107.87 50.06L108.98 50.54L110.00 51.11L110.94 51.75L111.77 52.47L112.50 53.24L113.13 54.05L113.65 54.90L114.06 55.76L114.36 56.64L114.57 57.50L114.67 58.35L114.67 59.18L114.58 59.96L114.41 60.70L114.17 61.39L113.85 62.01L113.48 62.57L113.06 63.05L112.60 63.45L112.11 63.78L111.61 64.02L111.10 64.18L110.59 64.25L110.09 64.25L109.62 64.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M108.00 19.00L111.84 19.61L115.58 20.55L119.18 21.80L122.62 23.36L125.88 25.20L128.92 27.30L131.74 29.65L134.30 32.20L136.61 34.95L138.63 37.86L140.37 40.91L141.81 44.07L142.95 47.30L143.78 50.59L144.32 53.90L144.54 57.21L144.48 60.49L144.12 63.71L143.48 66.85L142.57 69.88L141.41 72.78L140.01 75.53L138.39 78.11L136.56 80.50L134.56 82.70L132.39 84.67L130.08 86.42L127.66 87.93L125.14 89.20L122.55 90.23L119.92 91.00L117.27 91.53L114.62 91.81L111.99 91.85L109.41 91.65L106.89 91.23L104.46 90.59L102.13 89.74L99.93 88.70L97.86 87.48L95.94 86.10L94.18 84.58L92.60 82.93L91.20 81.17L89.99 79.33L88.96 77.41L88.14 75.44L87.51 73.44L87.07 71.43L86.83 69.42L86.77 67.44L86.90 65.50L87.20 63.61L87.66 61.80L88.28 60.07L89.04 58.45L89.93 56.93L90.94 55.54L92.04 54.27L93.24 53.14L94.51 52.15L95.84 51.30L97.20 50.61L98.60 50.06L100.00 49.65L101.40 49.39L102.78 49.27L104.13 49.29L105.44 49.43L106.69 49.69L107.87 50.06L108.98 50.54L110.00 51.11L110.94 51.75L111.77 52.47L112.50 53.24L113.13 54.05L113.65 54.90L114.06 55.76L114.36 56.64L114.57 57.50L114.67 58.35L114.67 59.18L114.58 59.96L114.41 60.70L114.17 61.39L113.85 62.01L113.48 62.57L113.06 63.05L112.60 63.45L112.11 63.78L111.61 64.02L111.10 64.18L110.59 64.25L110.09 64.25L109.62 64.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(134.30 32.20) rotate(195.03) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(140.01 75.53) rotate(267.15) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(106.89 91.23) rotate(-20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(86.83 69.42) rotate(53.38) scale(0.48)"/>
|
||||
<circle cx="109.62" cy="64.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="109.62" cy="64.18" r="1.5" fill="#e4c783"/>
|
||||
<path d="M68.00 139.00L64.16 139.61L60.42 140.55L56.82 141.80L53.38 143.36L50.12 145.20L47.08 147.30L44.26 149.65L41.70 152.20L39.39 154.95L37.37 157.86L35.63 160.91L34.19 164.07L33.05 167.30L32.22 170.59L31.68 173.90L31.46 177.21L31.52 180.49L31.88 183.71L32.52 186.85L33.43 189.88L34.59 192.78L35.99 195.53L37.61 198.11L39.44 200.50L41.44 202.70L43.61 204.67L45.92 206.42L48.34 207.93L50.86 209.20L53.45 210.23L56.08 211.00L58.73 211.53L61.38 211.81L64.01 211.85L66.59 211.65L69.11 211.23L71.54 210.59L73.87 209.74L76.07 208.70L78.14 207.48L80.06 206.10L81.82 204.58L83.40 202.93L84.80 201.17L86.01 199.33L87.04 197.41L87.86 195.44L88.49 193.44L88.93 191.43L89.17 189.42L89.23 187.44L89.10 185.50L88.80 183.61L88.34 181.80L87.72 180.07L86.96 178.45L86.07 176.93L85.06 175.54L83.96 174.27L82.76 173.14L81.49 172.15L80.16 171.30L78.80 170.61L77.40 170.06L76.00 169.65L74.60 169.39L73.22 169.27L71.87 169.29L70.56 169.43L69.31 169.69L68.13 170.06L67.02 170.54L66.00 171.11L65.06 171.75L64.23 172.47L63.50 173.24L62.87 174.05L62.35 174.90L61.94 175.76L61.64 176.64L61.43 177.50L61.33 178.35L61.33 179.18L61.42 179.96L61.59 180.70L61.83 181.39L62.15 182.01L62.52 182.57L62.94 183.05L63.40 183.45L63.89 183.78L64.39 184.02L64.90 184.18L65.41 184.25L65.91 184.25L66.38 184.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M68.00 139.00L64.16 139.61L60.42 140.55L56.82 141.80L53.38 143.36L50.12 145.20L47.08 147.30L44.26 149.65L41.70 152.20L39.39 154.95L37.37 157.86L35.63 160.91L34.19 164.07L33.05 167.30L32.22 170.59L31.68 173.90L31.46 177.21L31.52 180.49L31.88 183.71L32.52 186.85L33.43 189.88L34.59 192.78L35.99 195.53L37.61 198.11L39.44 200.50L41.44 202.70L43.61 204.67L45.92 206.42L48.34 207.93L50.86 209.20L53.45 210.23L56.08 211.00L58.73 211.53L61.38 211.81L64.01 211.85L66.59 211.65L69.11 211.23L71.54 210.59L73.87 209.74L76.07 208.70L78.14 207.48L80.06 206.10L81.82 204.58L83.40 202.93L84.80 201.17L86.01 199.33L87.04 197.41L87.86 195.44L88.49 193.44L88.93 191.43L89.17 189.42L89.23 187.44L89.10 185.50L88.80 183.61L88.34 181.80L87.72 180.07L86.96 178.45L86.07 176.93L85.06 175.54L83.96 174.27L82.76 173.14L81.49 172.15L80.16 171.30L78.80 170.61L77.40 170.06L76.00 169.65L74.60 169.39L73.22 169.27L71.87 169.29L70.56 169.43L69.31 169.69L68.13 170.06L67.02 170.54L66.00 171.11L65.06 171.75L64.23 172.47L63.50 173.24L62.87 174.05L62.35 174.90L61.94 175.76L61.64 176.64L61.43 177.50L61.33 178.35L61.33 179.18L61.42 179.96L61.59 180.70L61.83 181.39L62.15 182.01L62.52 182.57L62.94 183.05L63.40 183.45L63.89 183.78L64.39 184.02L64.90 184.18L65.41 184.25L65.91 184.25L66.38 184.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(41.70 152.20) rotate(164.97) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(35.99 195.53) rotate(92.85) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(69.11 211.23) rotate(20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(89.17 189.42) rotate(-53.38) scale(0.48)"/>
|
||||
<circle cx="66.38" cy="184.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="66.38" cy="184.18" r="1.5" fill="#e4c783"/>
|
||||
<use href="#leaf" transform="translate(95.32 16.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M95.32 16Q56.32 22 56.32 -4" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(56.32 -4.00) rotate(-25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(93.56 108.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M93.56 108Q132.56 114 132.56 88" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(132.56 88.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(80.68 136.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M80.68 136Q119.68 142 119.68 116" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(119.68 116.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(82.44 228.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M82.44 228Q43.44 234 43.44 208" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(43.44 208.00) rotate(-25.00) scale(0.55)"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(0)"/>
|
||||
<circle cx="58.00" cy="91.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(45)"/>
|
||||
<circle cx="54.19" cy="100.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(90)"/>
|
||||
<circle cx="45.00" cy="104.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(135)"/>
|
||||
<circle cx="35.81" cy="100.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(180)"/>
|
||||
<circle cx="32.00" cy="91.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(225)"/>
|
||||
<circle cx="35.81" cy="81.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(270)"/>
|
||||
<circle cx="45.00" cy="78.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 91) rotate(315)"/>
|
||||
<circle cx="54.19" cy="81.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="45.00" cy="91.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="45.00" cy="91.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M42 106q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M48 106q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(0)"/>
|
||||
<circle cx="152.00" cy="211.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(45)"/>
|
||||
<circle cx="148.19" cy="220.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(90)"/>
|
||||
<circle cx="139.00" cy="224.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(135)"/>
|
||||
<circle cx="129.81" cy="220.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(180)"/>
|
||||
<circle cx="126.00" cy="211.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(225)"/>
|
||||
<circle cx="129.81" cy="201.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(270)"/>
|
||||
<circle cx="139.00" cy="198.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 211) rotate(315)"/>
|
||||
<circle cx="148.19" cy="201.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="139.00" cy="211.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="139.00" cy="211.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M136 226q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M142 226q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<circle cx="158.00" cy="0.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="10.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="20.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="30.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="40.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="50.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="60.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="70.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="80.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="90.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="100.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="110.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="120.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="130.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="140.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="150.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="160.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="170.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="180.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="190.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="200.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="210.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="220.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="230.00" r="0.7" fill="#a58951"/>
|
||||
<path d="M151 15V25M147 20H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M151 135V145M147 140H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M88 240C150 300 26 420 88 480" fill="none" stroke="#594525" stroke-width="5"/>
|
||||
<path d="M88 240C150 300 26 420 88 480" fill="none" stroke="url(#gold)" stroke-width="3"/>
|
||||
<path d="M88 240C150 300 26 420 88 480" fill="none" stroke="#f0dab0" stroke-width="0.55"/>
|
||||
<path d="M108.00 259.00L111.84 259.61L115.58 260.55L119.18 261.80L122.62 263.36L125.88 265.20L128.92 267.30L131.74 269.65L134.30 272.20L136.61 274.95L138.63 277.86L140.37 280.91L141.81 284.07L142.95 287.30L143.78 290.59L144.32 293.90L144.54 297.21L144.48 300.49L144.12 303.71L143.48 306.85L142.57 309.88L141.41 312.78L140.01 315.53L138.39 318.11L136.56 320.50L134.56 322.70L132.39 324.67L130.08 326.42L127.66 327.93L125.14 329.20L122.55 330.23L119.92 331.00L117.27 331.53L114.62 331.81L111.99 331.85L109.41 331.65L106.89 331.23L104.46 330.59L102.13 329.74L99.93 328.70L97.86 327.48L95.94 326.10L94.18 324.58L92.60 322.93L91.20 321.17L89.99 319.33L88.96 317.41L88.14 315.44L87.51 313.44L87.07 311.43L86.83 309.42L86.77 307.44L86.90 305.50L87.20 303.61L87.66 301.80L88.28 300.07L89.04 298.45L89.93 296.93L90.94 295.54L92.04 294.27L93.24 293.14L94.51 292.15L95.84 291.30L97.20 290.61L98.60 290.06L100.00 289.65L101.40 289.39L102.78 289.27L104.13 289.29L105.44 289.43L106.69 289.69L107.87 290.06L108.98 290.54L110.00 291.11L110.94 291.75L111.77 292.47L112.50 293.24L113.13 294.05L113.65 294.90L114.06 295.76L114.36 296.64L114.57 297.50L114.67 298.35L114.67 299.18L114.58 299.96L114.41 300.70L114.17 301.39L113.85 302.01L113.48 302.57L113.06 303.05L112.60 303.45L112.11 303.78L111.61 304.02L111.10 304.18L110.59 304.25L110.09 304.25L109.62 304.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M108.00 259.00L111.84 259.61L115.58 260.55L119.18 261.80L122.62 263.36L125.88 265.20L128.92 267.30L131.74 269.65L134.30 272.20L136.61 274.95L138.63 277.86L140.37 280.91L141.81 284.07L142.95 287.30L143.78 290.59L144.32 293.90L144.54 297.21L144.48 300.49L144.12 303.71L143.48 306.85L142.57 309.88L141.41 312.78L140.01 315.53L138.39 318.11L136.56 320.50L134.56 322.70L132.39 324.67L130.08 326.42L127.66 327.93L125.14 329.20L122.55 330.23L119.92 331.00L117.27 331.53L114.62 331.81L111.99 331.85L109.41 331.65L106.89 331.23L104.46 330.59L102.13 329.74L99.93 328.70L97.86 327.48L95.94 326.10L94.18 324.58L92.60 322.93L91.20 321.17L89.99 319.33L88.96 317.41L88.14 315.44L87.51 313.44L87.07 311.43L86.83 309.42L86.77 307.44L86.90 305.50L87.20 303.61L87.66 301.80L88.28 300.07L89.04 298.45L89.93 296.93L90.94 295.54L92.04 294.27L93.24 293.14L94.51 292.15L95.84 291.30L97.20 290.61L98.60 290.06L100.00 289.65L101.40 289.39L102.78 289.27L104.13 289.29L105.44 289.43L106.69 289.69L107.87 290.06L108.98 290.54L110.00 291.11L110.94 291.75L111.77 292.47L112.50 293.24L113.13 294.05L113.65 294.90L114.06 295.76L114.36 296.64L114.57 297.50L114.67 298.35L114.67 299.18L114.58 299.96L114.41 300.70L114.17 301.39L113.85 302.01L113.48 302.57L113.06 303.05L112.60 303.45L112.11 303.78L111.61 304.02L111.10 304.18L110.59 304.25L110.09 304.25L109.62 304.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(134.30 272.20) rotate(195.03) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(140.01 315.53) rotate(267.15) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(106.89 331.23) rotate(-20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(86.83 309.42) rotate(53.38) scale(0.48)"/>
|
||||
<circle cx="109.62" cy="304.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="109.62" cy="304.18" r="1.5" fill="#e4c783"/>
|
||||
<path d="M68.00 379.00L64.16 379.61L60.42 380.55L56.82 381.80L53.38 383.36L50.12 385.20L47.08 387.30L44.26 389.65L41.70 392.20L39.39 394.95L37.37 397.86L35.63 400.91L34.19 404.07L33.05 407.30L32.22 410.59L31.68 413.90L31.46 417.21L31.52 420.49L31.88 423.71L32.52 426.85L33.43 429.88L34.59 432.78L35.99 435.53L37.61 438.11L39.44 440.50L41.44 442.70L43.61 444.67L45.92 446.42L48.34 447.93L50.86 449.20L53.45 450.23L56.08 451.00L58.73 451.53L61.38 451.81L64.01 451.85L66.59 451.65L69.11 451.23L71.54 450.59L73.87 449.74L76.07 448.70L78.14 447.48L80.06 446.10L81.82 444.58L83.40 442.93L84.80 441.17L86.01 439.33L87.04 437.41L87.86 435.44L88.49 433.44L88.93 431.43L89.17 429.42L89.23 427.44L89.10 425.50L88.80 423.61L88.34 421.80L87.72 420.07L86.96 418.45L86.07 416.93L85.06 415.54L83.96 414.27L82.76 413.14L81.49 412.15L80.16 411.30L78.80 410.61L77.40 410.06L76.00 409.65L74.60 409.39L73.22 409.27L71.87 409.29L70.56 409.43L69.31 409.69L68.13 410.06L67.02 410.54L66.00 411.11L65.06 411.75L64.23 412.47L63.50 413.24L62.87 414.05L62.35 414.90L61.94 415.76L61.64 416.64L61.43 417.50L61.33 418.35L61.33 419.18L61.42 419.96L61.59 420.70L61.83 421.39L62.15 422.01L62.52 422.57L62.94 423.05L63.40 423.45L63.89 423.78L64.39 424.02L64.90 424.18L65.41 424.25L65.91 424.25L66.38 424.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M68.00 379.00L64.16 379.61L60.42 380.55L56.82 381.80L53.38 383.36L50.12 385.20L47.08 387.30L44.26 389.65L41.70 392.20L39.39 394.95L37.37 397.86L35.63 400.91L34.19 404.07L33.05 407.30L32.22 410.59L31.68 413.90L31.46 417.21L31.52 420.49L31.88 423.71L32.52 426.85L33.43 429.88L34.59 432.78L35.99 435.53L37.61 438.11L39.44 440.50L41.44 442.70L43.61 444.67L45.92 446.42L48.34 447.93L50.86 449.20L53.45 450.23L56.08 451.00L58.73 451.53L61.38 451.81L64.01 451.85L66.59 451.65L69.11 451.23L71.54 450.59L73.87 449.74L76.07 448.70L78.14 447.48L80.06 446.10L81.82 444.58L83.40 442.93L84.80 441.17L86.01 439.33L87.04 437.41L87.86 435.44L88.49 433.44L88.93 431.43L89.17 429.42L89.23 427.44L89.10 425.50L88.80 423.61L88.34 421.80L87.72 420.07L86.96 418.45L86.07 416.93L85.06 415.54L83.96 414.27L82.76 413.14L81.49 412.15L80.16 411.30L78.80 410.61L77.40 410.06L76.00 409.65L74.60 409.39L73.22 409.27L71.87 409.29L70.56 409.43L69.31 409.69L68.13 410.06L67.02 410.54L66.00 411.11L65.06 411.75L64.23 412.47L63.50 413.24L62.87 414.05L62.35 414.90L61.94 415.76L61.64 416.64L61.43 417.50L61.33 418.35L61.33 419.18L61.42 419.96L61.59 420.70L61.83 421.39L62.15 422.01L62.52 422.57L62.94 423.05L63.40 423.45L63.89 423.78L64.39 424.02L64.90 424.18L65.41 424.25L65.91 424.25L66.38 424.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(41.70 392.20) rotate(164.97) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(35.99 435.53) rotate(92.85) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(69.11 451.23) rotate(20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(89.17 429.42) rotate(-53.38) scale(0.48)"/>
|
||||
<circle cx="66.38" cy="424.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="66.38" cy="424.18" r="1.5" fill="#e4c783"/>
|
||||
<use href="#leaf" transform="translate(95.32 256.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M95.32 256Q56.32 262 56.32 236" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(56.32 236.00) rotate(-25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(93.56 348.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M93.56 348Q132.56 354 132.56 328" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(132.56 328.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(80.68 376.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M80.68 376Q119.68 382 119.68 356" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(119.68 356.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(82.44 468.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M82.44 468Q43.44 474 43.44 448" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(43.44 448.00) rotate(-25.00) scale(0.55)"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(0)"/>
|
||||
<circle cx="58.00" cy="331.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(45)"/>
|
||||
<circle cx="54.19" cy="340.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(90)"/>
|
||||
<circle cx="45.00" cy="344.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(135)"/>
|
||||
<circle cx="35.81" cy="340.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(180)"/>
|
||||
<circle cx="32.00" cy="331.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(225)"/>
|
||||
<circle cx="35.81" cy="321.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(270)"/>
|
||||
<circle cx="45.00" cy="318.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 331) rotate(315)"/>
|
||||
<circle cx="54.19" cy="321.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="45.00" cy="331.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="45.00" cy="331.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M42 346q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M48 346q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(0)"/>
|
||||
<circle cx="152.00" cy="451.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(45)"/>
|
||||
<circle cx="148.19" cy="460.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(90)"/>
|
||||
<circle cx="139.00" cy="464.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(135)"/>
|
||||
<circle cx="129.81" cy="460.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(180)"/>
|
||||
<circle cx="126.00" cy="451.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(225)"/>
|
||||
<circle cx="129.81" cy="441.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(270)"/>
|
||||
<circle cx="139.00" cy="438.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 451) rotate(315)"/>
|
||||
<circle cx="148.19" cy="441.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="139.00" cy="451.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="139.00" cy="451.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M136 466q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M142 466q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<circle cx="158.00" cy="240.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="250.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="260.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="270.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="280.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="290.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="300.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="310.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="320.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="330.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="340.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="350.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="360.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="370.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="380.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="390.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="400.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="410.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="420.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="430.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="440.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="450.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="460.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="470.00" r="0.7" fill="#a58951"/>
|
||||
<path d="M151 255V265M147 260H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M151 375V385M147 380H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M88 480C150 540 26 660 88 720" fill="none" stroke="#594525" stroke-width="5"/>
|
||||
<path d="M88 480C150 540 26 660 88 720" fill="none" stroke="url(#gold)" stroke-width="3"/>
|
||||
<path d="M88 480C150 540 26 660 88 720" fill="none" stroke="#f0dab0" stroke-width="0.55"/>
|
||||
<path d="M108.00 499.00L111.84 499.61L115.58 500.55L119.18 501.80L122.62 503.36L125.88 505.20L128.92 507.30L131.74 509.65L134.30 512.20L136.61 514.95L138.63 517.86L140.37 520.91L141.81 524.07L142.95 527.30L143.78 530.59L144.32 533.90L144.54 537.21L144.48 540.49L144.12 543.71L143.48 546.85L142.57 549.88L141.41 552.78L140.01 555.53L138.39 558.11L136.56 560.50L134.56 562.70L132.39 564.67L130.08 566.42L127.66 567.93L125.14 569.20L122.55 570.23L119.92 571.00L117.27 571.53L114.62 571.81L111.99 571.85L109.41 571.65L106.89 571.23L104.46 570.59L102.13 569.74L99.93 568.70L97.86 567.48L95.94 566.10L94.18 564.58L92.60 562.93L91.20 561.17L89.99 559.33L88.96 557.41L88.14 555.44L87.51 553.44L87.07 551.43L86.83 549.42L86.77 547.44L86.90 545.50L87.20 543.61L87.66 541.80L88.28 540.07L89.04 538.45L89.93 536.93L90.94 535.54L92.04 534.27L93.24 533.14L94.51 532.15L95.84 531.30L97.20 530.61L98.60 530.06L100.00 529.65L101.40 529.39L102.78 529.27L104.13 529.29L105.44 529.43L106.69 529.69L107.87 530.06L108.98 530.54L110.00 531.11L110.94 531.75L111.77 532.47L112.50 533.24L113.13 534.05L113.65 534.90L114.06 535.76L114.36 536.64L114.57 537.50L114.67 538.35L114.67 539.18L114.58 539.96L114.41 540.70L114.17 541.39L113.85 542.01L113.48 542.57L113.06 543.05L112.60 543.45L112.11 543.78L111.61 544.02L111.10 544.18L110.59 544.25L110.09 544.25L109.62 544.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M108.00 499.00L111.84 499.61L115.58 500.55L119.18 501.80L122.62 503.36L125.88 505.20L128.92 507.30L131.74 509.65L134.30 512.20L136.61 514.95L138.63 517.86L140.37 520.91L141.81 524.07L142.95 527.30L143.78 530.59L144.32 533.90L144.54 537.21L144.48 540.49L144.12 543.71L143.48 546.85L142.57 549.88L141.41 552.78L140.01 555.53L138.39 558.11L136.56 560.50L134.56 562.70L132.39 564.67L130.08 566.42L127.66 567.93L125.14 569.20L122.55 570.23L119.92 571.00L117.27 571.53L114.62 571.81L111.99 571.85L109.41 571.65L106.89 571.23L104.46 570.59L102.13 569.74L99.93 568.70L97.86 567.48L95.94 566.10L94.18 564.58L92.60 562.93L91.20 561.17L89.99 559.33L88.96 557.41L88.14 555.44L87.51 553.44L87.07 551.43L86.83 549.42L86.77 547.44L86.90 545.50L87.20 543.61L87.66 541.80L88.28 540.07L89.04 538.45L89.93 536.93L90.94 535.54L92.04 534.27L93.24 533.14L94.51 532.15L95.84 531.30L97.20 530.61L98.60 530.06L100.00 529.65L101.40 529.39L102.78 529.27L104.13 529.29L105.44 529.43L106.69 529.69L107.87 530.06L108.98 530.54L110.00 531.11L110.94 531.75L111.77 532.47L112.50 533.24L113.13 534.05L113.65 534.90L114.06 535.76L114.36 536.64L114.57 537.50L114.67 538.35L114.67 539.18L114.58 539.96L114.41 540.70L114.17 541.39L113.85 542.01L113.48 542.57L113.06 543.05L112.60 543.45L112.11 543.78L111.61 544.02L111.10 544.18L110.59 544.25L110.09 544.25L109.62 544.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(134.30 512.20) rotate(195.03) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(140.01 555.53) rotate(267.15) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(106.89 571.23) rotate(-20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(86.83 549.42) rotate(53.38) scale(0.48)"/>
|
||||
<circle cx="109.62" cy="544.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="109.62" cy="544.18" r="1.5" fill="#e4c783"/>
|
||||
<path d="M68.00 619.00L64.16 619.61L60.42 620.55L56.82 621.80L53.38 623.36L50.12 625.20L47.08 627.30L44.26 629.65L41.70 632.20L39.39 634.95L37.37 637.86L35.63 640.91L34.19 644.07L33.05 647.30L32.22 650.59L31.68 653.90L31.46 657.21L31.52 660.49L31.88 663.71L32.52 666.85L33.43 669.88L34.59 672.78L35.99 675.53L37.61 678.11L39.44 680.50L41.44 682.70L43.61 684.67L45.92 686.42L48.34 687.93L50.86 689.20L53.45 690.23L56.08 691.00L58.73 691.53L61.38 691.81L64.01 691.85L66.59 691.65L69.11 691.23L71.54 690.59L73.87 689.74L76.07 688.70L78.14 687.48L80.06 686.10L81.82 684.58L83.40 682.93L84.80 681.17L86.01 679.33L87.04 677.41L87.86 675.44L88.49 673.44L88.93 671.43L89.17 669.42L89.23 667.44L89.10 665.50L88.80 663.61L88.34 661.80L87.72 660.07L86.96 658.45L86.07 656.93L85.06 655.54L83.96 654.27L82.76 653.14L81.49 652.15L80.16 651.30L78.80 650.61L77.40 650.06L76.00 649.65L74.60 649.39L73.22 649.27L71.87 649.29L70.56 649.43L69.31 649.69L68.13 650.06L67.02 650.54L66.00 651.11L65.06 651.75L64.23 652.47L63.50 653.24L62.87 654.05L62.35 654.90L61.94 655.76L61.64 656.64L61.43 657.50L61.33 658.35L61.33 659.18L61.42 659.96L61.59 660.70L61.83 661.39L62.15 662.01L62.52 662.57L62.94 663.05L63.40 663.45L63.89 663.78L64.39 664.02L64.90 664.18L65.41 664.25L65.91 664.25L66.38 664.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M68.00 619.00L64.16 619.61L60.42 620.55L56.82 621.80L53.38 623.36L50.12 625.20L47.08 627.30L44.26 629.65L41.70 632.20L39.39 634.95L37.37 637.86L35.63 640.91L34.19 644.07L33.05 647.30L32.22 650.59L31.68 653.90L31.46 657.21L31.52 660.49L31.88 663.71L32.52 666.85L33.43 669.88L34.59 672.78L35.99 675.53L37.61 678.11L39.44 680.50L41.44 682.70L43.61 684.67L45.92 686.42L48.34 687.93L50.86 689.20L53.45 690.23L56.08 691.00L58.73 691.53L61.38 691.81L64.01 691.85L66.59 691.65L69.11 691.23L71.54 690.59L73.87 689.74L76.07 688.70L78.14 687.48L80.06 686.10L81.82 684.58L83.40 682.93L84.80 681.17L86.01 679.33L87.04 677.41L87.86 675.44L88.49 673.44L88.93 671.43L89.17 669.42L89.23 667.44L89.10 665.50L88.80 663.61L88.34 661.80L87.72 660.07L86.96 658.45L86.07 656.93L85.06 655.54L83.96 654.27L82.76 653.14L81.49 652.15L80.16 651.30L78.80 650.61L77.40 650.06L76.00 649.65L74.60 649.39L73.22 649.27L71.87 649.29L70.56 649.43L69.31 649.69L68.13 650.06L67.02 650.54L66.00 651.11L65.06 651.75L64.23 652.47L63.50 653.24L62.87 654.05L62.35 654.90L61.94 655.76L61.64 656.64L61.43 657.50L61.33 658.35L61.33 659.18L61.42 659.96L61.59 660.70L61.83 661.39L62.15 662.01L62.52 662.57L62.94 663.05L63.40 663.45L63.89 663.78L64.39 664.02L64.90 664.18L65.41 664.25L65.91 664.25L66.38 664.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(41.70 632.20) rotate(164.97) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(35.99 675.53) rotate(92.85) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(69.11 691.23) rotate(20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(89.17 669.42) rotate(-53.38) scale(0.48)"/>
|
||||
<circle cx="66.38" cy="664.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="66.38" cy="664.18" r="1.5" fill="#e4c783"/>
|
||||
<use href="#leaf" transform="translate(95.32 496.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M95.32 496Q56.32 502 56.32 476" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(56.32 476.00) rotate(-25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(93.56 588.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M93.56 588Q132.56 594 132.56 568" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(132.56 568.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(80.68 616.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M80.68 616Q119.68 622 119.68 596" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(119.68 596.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(82.44 708.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M82.44 708Q43.44 714 43.44 688" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(43.44 688.00) rotate(-25.00) scale(0.55)"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(0)"/>
|
||||
<circle cx="58.00" cy="571.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(45)"/>
|
||||
<circle cx="54.19" cy="580.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(90)"/>
|
||||
<circle cx="45.00" cy="584.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(135)"/>
|
||||
<circle cx="35.81" cy="580.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(180)"/>
|
||||
<circle cx="32.00" cy="571.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(225)"/>
|
||||
<circle cx="35.81" cy="561.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(270)"/>
|
||||
<circle cx="45.00" cy="558.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 571) rotate(315)"/>
|
||||
<circle cx="54.19" cy="561.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="45.00" cy="571.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="45.00" cy="571.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M42 586q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M48 586q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(0)"/>
|
||||
<circle cx="152.00" cy="691.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(45)"/>
|
||||
<circle cx="148.19" cy="700.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(90)"/>
|
||||
<circle cx="139.00" cy="704.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(135)"/>
|
||||
<circle cx="129.81" cy="700.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(180)"/>
|
||||
<circle cx="126.00" cy="691.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(225)"/>
|
||||
<circle cx="129.81" cy="681.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(270)"/>
|
||||
<circle cx="139.00" cy="678.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 691) rotate(315)"/>
|
||||
<circle cx="148.19" cy="681.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="139.00" cy="691.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="139.00" cy="691.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M136 706q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M142 706q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<circle cx="158.00" cy="480.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="490.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="500.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="510.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="520.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="530.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="540.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="550.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="560.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="570.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="580.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="590.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="600.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="610.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="620.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="630.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="640.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="650.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="660.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="670.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="680.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="690.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="700.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="710.00" r="0.7" fill="#a58951"/>
|
||||
<path d="M151 495V505M147 500H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M151 615V625M147 620H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M88 720C150 780 26 900 88 960" fill="none" stroke="#594525" stroke-width="5"/>
|
||||
<path d="M88 720C150 780 26 900 88 960" fill="none" stroke="url(#gold)" stroke-width="3"/>
|
||||
<path d="M88 720C150 780 26 900 88 960" fill="none" stroke="#f0dab0" stroke-width="0.55"/>
|
||||
<path d="M108.00 739.00L111.84 739.61L115.58 740.55L119.18 741.80L122.62 743.36L125.88 745.20L128.92 747.30L131.74 749.65L134.30 752.20L136.61 754.95L138.63 757.86L140.37 760.91L141.81 764.07L142.95 767.30L143.78 770.59L144.32 773.90L144.54 777.21L144.48 780.49L144.12 783.71L143.48 786.85L142.57 789.88L141.41 792.78L140.01 795.53L138.39 798.11L136.56 800.50L134.56 802.70L132.39 804.67L130.08 806.42L127.66 807.93L125.14 809.20L122.55 810.23L119.92 811.00L117.27 811.53L114.62 811.81L111.99 811.85L109.41 811.65L106.89 811.23L104.46 810.59L102.13 809.74L99.93 808.70L97.86 807.48L95.94 806.10L94.18 804.58L92.60 802.93L91.20 801.17L89.99 799.33L88.96 797.41L88.14 795.44L87.51 793.44L87.07 791.43L86.83 789.42L86.77 787.44L86.90 785.50L87.20 783.61L87.66 781.80L88.28 780.07L89.04 778.45L89.93 776.93L90.94 775.54L92.04 774.27L93.24 773.14L94.51 772.15L95.84 771.30L97.20 770.61L98.60 770.06L100.00 769.65L101.40 769.39L102.78 769.27L104.13 769.29L105.44 769.43L106.69 769.69L107.87 770.06L108.98 770.54L110.00 771.11L110.94 771.75L111.77 772.47L112.50 773.24L113.13 774.05L113.65 774.90L114.06 775.76L114.36 776.64L114.57 777.50L114.67 778.35L114.67 779.18L114.58 779.96L114.41 780.70L114.17 781.39L113.85 782.01L113.48 782.57L113.06 783.05L112.60 783.45L112.11 783.78L111.61 784.02L111.10 784.18L110.59 784.25L110.09 784.25L109.62 784.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M108.00 739.00L111.84 739.61L115.58 740.55L119.18 741.80L122.62 743.36L125.88 745.20L128.92 747.30L131.74 749.65L134.30 752.20L136.61 754.95L138.63 757.86L140.37 760.91L141.81 764.07L142.95 767.30L143.78 770.59L144.32 773.90L144.54 777.21L144.48 780.49L144.12 783.71L143.48 786.85L142.57 789.88L141.41 792.78L140.01 795.53L138.39 798.11L136.56 800.50L134.56 802.70L132.39 804.67L130.08 806.42L127.66 807.93L125.14 809.20L122.55 810.23L119.92 811.00L117.27 811.53L114.62 811.81L111.99 811.85L109.41 811.65L106.89 811.23L104.46 810.59L102.13 809.74L99.93 808.70L97.86 807.48L95.94 806.10L94.18 804.58L92.60 802.93L91.20 801.17L89.99 799.33L88.96 797.41L88.14 795.44L87.51 793.44L87.07 791.43L86.83 789.42L86.77 787.44L86.90 785.50L87.20 783.61L87.66 781.80L88.28 780.07L89.04 778.45L89.93 776.93L90.94 775.54L92.04 774.27L93.24 773.14L94.51 772.15L95.84 771.30L97.20 770.61L98.60 770.06L100.00 769.65L101.40 769.39L102.78 769.27L104.13 769.29L105.44 769.43L106.69 769.69L107.87 770.06L108.98 770.54L110.00 771.11L110.94 771.75L111.77 772.47L112.50 773.24L113.13 774.05L113.65 774.90L114.06 775.76L114.36 776.64L114.57 777.50L114.67 778.35L114.67 779.18L114.58 779.96L114.41 780.70L114.17 781.39L113.85 782.01L113.48 782.57L113.06 783.05L112.60 783.45L112.11 783.78L111.61 784.02L111.10 784.18L110.59 784.25L110.09 784.25L109.62 784.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(134.30 752.20) rotate(195.03) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(140.01 795.53) rotate(267.15) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(106.89 811.23) rotate(-20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(86.83 789.42) rotate(53.38) scale(0.48)"/>
|
||||
<circle cx="109.62" cy="784.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="109.62" cy="784.18" r="1.5" fill="#e4c783"/>
|
||||
<path d="M68.00 859.00L64.16 859.61L60.42 860.55L56.82 861.80L53.38 863.36L50.12 865.20L47.08 867.30L44.26 869.65L41.70 872.20L39.39 874.95L37.37 877.86L35.63 880.91L34.19 884.07L33.05 887.30L32.22 890.59L31.68 893.90L31.46 897.21L31.52 900.49L31.88 903.71L32.52 906.85L33.43 909.88L34.59 912.78L35.99 915.53L37.61 918.11L39.44 920.50L41.44 922.70L43.61 924.67L45.92 926.42L48.34 927.93L50.86 929.20L53.45 930.23L56.08 931.00L58.73 931.53L61.38 931.81L64.01 931.85L66.59 931.65L69.11 931.23L71.54 930.59L73.87 929.74L76.07 928.70L78.14 927.48L80.06 926.10L81.82 924.58L83.40 922.93L84.80 921.17L86.01 919.33L87.04 917.41L87.86 915.44L88.49 913.44L88.93 911.43L89.17 909.42L89.23 907.44L89.10 905.50L88.80 903.61L88.34 901.80L87.72 900.07L86.96 898.45L86.07 896.93L85.06 895.54L83.96 894.27L82.76 893.14L81.49 892.15L80.16 891.30L78.80 890.61L77.40 890.06L76.00 889.65L74.60 889.39L73.22 889.27L71.87 889.29L70.56 889.43L69.31 889.69L68.13 890.06L67.02 890.54L66.00 891.11L65.06 891.75L64.23 892.47L63.50 893.24L62.87 894.05L62.35 894.90L61.94 895.76L61.64 896.64L61.43 897.50L61.33 898.35L61.33 899.18L61.42 899.96L61.59 900.70L61.83 901.39L62.15 902.01L62.52 902.57L62.94 903.05L63.40 903.45L63.89 903.78L64.39 904.02L64.90 904.18L65.41 904.25L65.91 904.25L66.38 904.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M68.00 859.00L64.16 859.61L60.42 860.55L56.82 861.80L53.38 863.36L50.12 865.20L47.08 867.30L44.26 869.65L41.70 872.20L39.39 874.95L37.37 877.86L35.63 880.91L34.19 884.07L33.05 887.30L32.22 890.59L31.68 893.90L31.46 897.21L31.52 900.49L31.88 903.71L32.52 906.85L33.43 909.88L34.59 912.78L35.99 915.53L37.61 918.11L39.44 920.50L41.44 922.70L43.61 924.67L45.92 926.42L48.34 927.93L50.86 929.20L53.45 930.23L56.08 931.00L58.73 931.53L61.38 931.81L64.01 931.85L66.59 931.65L69.11 931.23L71.54 930.59L73.87 929.74L76.07 928.70L78.14 927.48L80.06 926.10L81.82 924.58L83.40 922.93L84.80 921.17L86.01 919.33L87.04 917.41L87.86 915.44L88.49 913.44L88.93 911.43L89.17 909.42L89.23 907.44L89.10 905.50L88.80 903.61L88.34 901.80L87.72 900.07L86.96 898.45L86.07 896.93L85.06 895.54L83.96 894.27L82.76 893.14L81.49 892.15L80.16 891.30L78.80 890.61L77.40 890.06L76.00 889.65L74.60 889.39L73.22 889.27L71.87 889.29L70.56 889.43L69.31 889.69L68.13 890.06L67.02 890.54L66.00 891.11L65.06 891.75L64.23 892.47L63.50 893.24L62.87 894.05L62.35 894.90L61.94 895.76L61.64 896.64L61.43 897.50L61.33 898.35L61.33 899.18L61.42 899.96L61.59 900.70L61.83 901.39L62.15 902.01L62.52 902.57L62.94 903.05L63.40 903.45L63.89 903.78L64.39 904.02L64.90 904.18L65.41 904.25L65.91 904.25L66.38 904.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(41.70 872.20) rotate(164.97) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(35.99 915.53) rotate(92.85) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(69.11 931.23) rotate(20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(89.17 909.42) rotate(-53.38) scale(0.48)"/>
|
||||
<circle cx="66.38" cy="904.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="66.38" cy="904.18" r="1.5" fill="#e4c783"/>
|
||||
<use href="#leaf" transform="translate(95.32 736.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M95.32 736Q56.32 742 56.32 716" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(56.32 716.00) rotate(-25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(93.56 828.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M93.56 828Q132.56 834 132.56 808" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(132.56 808.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(80.68 856.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M80.68 856Q119.68 862 119.68 836" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(119.68 836.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(82.44 948.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M82.44 948Q43.44 954 43.44 928" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(43.44 928.00) rotate(-25.00) scale(0.55)"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(0)"/>
|
||||
<circle cx="58.00" cy="811.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(45)"/>
|
||||
<circle cx="54.19" cy="820.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(90)"/>
|
||||
<circle cx="45.00" cy="824.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(135)"/>
|
||||
<circle cx="35.81" cy="820.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(180)"/>
|
||||
<circle cx="32.00" cy="811.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(225)"/>
|
||||
<circle cx="35.81" cy="801.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(270)"/>
|
||||
<circle cx="45.00" cy="798.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 811) rotate(315)"/>
|
||||
<circle cx="54.19" cy="801.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="45.00" cy="811.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="45.00" cy="811.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M42 826q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M48 826q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(0)"/>
|
||||
<circle cx="152.00" cy="931.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(45)"/>
|
||||
<circle cx="148.19" cy="940.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(90)"/>
|
||||
<circle cx="139.00" cy="944.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(135)"/>
|
||||
<circle cx="129.81" cy="940.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(180)"/>
|
||||
<circle cx="126.00" cy="931.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(225)"/>
|
||||
<circle cx="129.81" cy="921.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(270)"/>
|
||||
<circle cx="139.00" cy="918.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 931) rotate(315)"/>
|
||||
<circle cx="148.19" cy="921.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="139.00" cy="931.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="139.00" cy="931.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M136 946q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M142 946q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<circle cx="158.00" cy="720.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="730.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="740.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="750.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="760.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="770.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="780.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="790.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="800.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="810.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="820.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="830.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="840.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="850.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="860.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="870.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="880.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="890.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="900.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="910.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="920.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="930.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="940.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="950.00" r="0.7" fill="#a58951"/>
|
||||
<path d="M151 735V745M147 740H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M151 855V865M147 860H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M88 960C150 1020 26 1140 88 1200" fill="none" stroke="#594525" stroke-width="5"/>
|
||||
<path d="M88 960C150 1020 26 1140 88 1200" fill="none" stroke="url(#gold)" stroke-width="3"/>
|
||||
<path d="M88 960C150 1020 26 1140 88 1200" fill="none" stroke="#f0dab0" stroke-width="0.55"/>
|
||||
<path d="M108.00 979.00L111.84 979.61L115.58 980.55L119.18 981.80L122.62 983.36L125.88 985.20L128.92 987.30L131.74 989.65L134.30 992.20L136.61 994.95L138.63 997.86L140.37 1000.91L141.81 1004.07L142.95 1007.30L143.78 1010.59L144.32 1013.90L144.54 1017.21L144.48 1020.49L144.12 1023.71L143.48 1026.85L142.57 1029.88L141.41 1032.78L140.01 1035.53L138.39 1038.11L136.56 1040.50L134.56 1042.70L132.39 1044.67L130.08 1046.42L127.66 1047.93L125.14 1049.20L122.55 1050.23L119.92 1051.00L117.27 1051.53L114.62 1051.81L111.99 1051.85L109.41 1051.65L106.89 1051.23L104.46 1050.59L102.13 1049.74L99.93 1048.70L97.86 1047.48L95.94 1046.10L94.18 1044.58L92.60 1042.93L91.20 1041.17L89.99 1039.33L88.96 1037.41L88.14 1035.44L87.51 1033.44L87.07 1031.43L86.83 1029.42L86.77 1027.44L86.90 1025.50L87.20 1023.61L87.66 1021.80L88.28 1020.07L89.04 1018.45L89.93 1016.93L90.94 1015.54L92.04 1014.27L93.24 1013.14L94.51 1012.15L95.84 1011.30L97.20 1010.61L98.60 1010.06L100.00 1009.65L101.40 1009.39L102.78 1009.27L104.13 1009.29L105.44 1009.43L106.69 1009.69L107.87 1010.06L108.98 1010.54L110.00 1011.11L110.94 1011.75L111.77 1012.47L112.50 1013.24L113.13 1014.05L113.65 1014.90L114.06 1015.76L114.36 1016.64L114.57 1017.50L114.67 1018.35L114.67 1019.18L114.58 1019.96L114.41 1020.70L114.17 1021.39L113.85 1022.01L113.48 1022.57L113.06 1023.05L112.60 1023.45L112.11 1023.78L111.61 1024.02L111.10 1024.18L110.59 1024.25L110.09 1024.25L109.62 1024.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M108.00 979.00L111.84 979.61L115.58 980.55L119.18 981.80L122.62 983.36L125.88 985.20L128.92 987.30L131.74 989.65L134.30 992.20L136.61 994.95L138.63 997.86L140.37 1000.91L141.81 1004.07L142.95 1007.30L143.78 1010.59L144.32 1013.90L144.54 1017.21L144.48 1020.49L144.12 1023.71L143.48 1026.85L142.57 1029.88L141.41 1032.78L140.01 1035.53L138.39 1038.11L136.56 1040.50L134.56 1042.70L132.39 1044.67L130.08 1046.42L127.66 1047.93L125.14 1049.20L122.55 1050.23L119.92 1051.00L117.27 1051.53L114.62 1051.81L111.99 1051.85L109.41 1051.65L106.89 1051.23L104.46 1050.59L102.13 1049.74L99.93 1048.70L97.86 1047.48L95.94 1046.10L94.18 1044.58L92.60 1042.93L91.20 1041.17L89.99 1039.33L88.96 1037.41L88.14 1035.44L87.51 1033.44L87.07 1031.43L86.83 1029.42L86.77 1027.44L86.90 1025.50L87.20 1023.61L87.66 1021.80L88.28 1020.07L89.04 1018.45L89.93 1016.93L90.94 1015.54L92.04 1014.27L93.24 1013.14L94.51 1012.15L95.84 1011.30L97.20 1010.61L98.60 1010.06L100.00 1009.65L101.40 1009.39L102.78 1009.27L104.13 1009.29L105.44 1009.43L106.69 1009.69L107.87 1010.06L108.98 1010.54L110.00 1011.11L110.94 1011.75L111.77 1012.47L112.50 1013.24L113.13 1014.05L113.65 1014.90L114.06 1015.76L114.36 1016.64L114.57 1017.50L114.67 1018.35L114.67 1019.18L114.58 1019.96L114.41 1020.70L114.17 1021.39L113.85 1022.01L113.48 1022.57L113.06 1023.05L112.60 1023.45L112.11 1023.78L111.61 1024.02L111.10 1024.18L110.59 1024.25L110.09 1024.25L109.62 1024.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(134.30 992.20) rotate(195.03) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(140.01 1035.53) rotate(267.15) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(106.89 1051.23) rotate(-20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(86.83 1029.42) rotate(53.38) scale(0.48)"/>
|
||||
<circle cx="109.62" cy="1024.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="109.62" cy="1024.18" r="1.5" fill="#e4c783"/>
|
||||
<path d="M68.00 1099.00L64.16 1099.61L60.42 1100.55L56.82 1101.80L53.38 1103.36L50.12 1105.20L47.08 1107.30L44.26 1109.65L41.70 1112.20L39.39 1114.95L37.37 1117.86L35.63 1120.91L34.19 1124.07L33.05 1127.30L32.22 1130.59L31.68 1133.90L31.46 1137.21L31.52 1140.49L31.88 1143.71L32.52 1146.85L33.43 1149.88L34.59 1152.78L35.99 1155.53L37.61 1158.11L39.44 1160.50L41.44 1162.70L43.61 1164.67L45.92 1166.42L48.34 1167.93L50.86 1169.20L53.45 1170.23L56.08 1171.00L58.73 1171.53L61.38 1171.81L64.01 1171.85L66.59 1171.65L69.11 1171.23L71.54 1170.59L73.87 1169.74L76.07 1168.70L78.14 1167.48L80.06 1166.10L81.82 1164.58L83.40 1162.93L84.80 1161.17L86.01 1159.33L87.04 1157.41L87.86 1155.44L88.49 1153.44L88.93 1151.43L89.17 1149.42L89.23 1147.44L89.10 1145.50L88.80 1143.61L88.34 1141.80L87.72 1140.07L86.96 1138.45L86.07 1136.93L85.06 1135.54L83.96 1134.27L82.76 1133.14L81.49 1132.15L80.16 1131.30L78.80 1130.61L77.40 1130.06L76.00 1129.65L74.60 1129.39L73.22 1129.27L71.87 1129.29L70.56 1129.43L69.31 1129.69L68.13 1130.06L67.02 1130.54L66.00 1131.11L65.06 1131.75L64.23 1132.47L63.50 1133.24L62.87 1134.05L62.35 1134.90L61.94 1135.76L61.64 1136.64L61.43 1137.50L61.33 1138.35L61.33 1139.18L61.42 1139.96L61.59 1140.70L61.83 1141.39L62.15 1142.01L62.52 1142.57L62.94 1143.05L63.40 1143.45L63.89 1143.78L64.39 1144.02L64.90 1144.18L65.41 1144.25L65.91 1144.25L66.38 1144.18" fill="none" stroke="#594525" stroke-width="2.8"/>
|
||||
<path d="M68.00 1099.00L64.16 1099.61L60.42 1100.55L56.82 1101.80L53.38 1103.36L50.12 1105.20L47.08 1107.30L44.26 1109.65L41.70 1112.20L39.39 1114.95L37.37 1117.86L35.63 1120.91L34.19 1124.07L33.05 1127.30L32.22 1130.59L31.68 1133.90L31.46 1137.21L31.52 1140.49L31.88 1143.71L32.52 1146.85L33.43 1149.88L34.59 1152.78L35.99 1155.53L37.61 1158.11L39.44 1160.50L41.44 1162.70L43.61 1164.67L45.92 1166.42L48.34 1167.93L50.86 1169.20L53.45 1170.23L56.08 1171.00L58.73 1171.53L61.38 1171.81L64.01 1171.85L66.59 1171.65L69.11 1171.23L71.54 1170.59L73.87 1169.74L76.07 1168.70L78.14 1167.48L80.06 1166.10L81.82 1164.58L83.40 1162.93L84.80 1161.17L86.01 1159.33L87.04 1157.41L87.86 1155.44L88.49 1153.44L88.93 1151.43L89.17 1149.42L89.23 1147.44L89.10 1145.50L88.80 1143.61L88.34 1141.80L87.72 1140.07L86.96 1138.45L86.07 1136.93L85.06 1135.54L83.96 1134.27L82.76 1133.14L81.49 1132.15L80.16 1131.30L78.80 1130.61L77.40 1130.06L76.00 1129.65L74.60 1129.39L73.22 1129.27L71.87 1129.29L70.56 1129.43L69.31 1129.69L68.13 1130.06L67.02 1130.54L66.00 1131.11L65.06 1131.75L64.23 1132.47L63.50 1133.24L62.87 1134.05L62.35 1134.90L61.94 1135.76L61.64 1136.64L61.43 1137.50L61.33 1138.35L61.33 1139.18L61.42 1139.96L61.59 1140.70L61.83 1141.39L62.15 1142.01L62.52 1142.57L62.94 1143.05L63.40 1143.45L63.89 1143.78L64.39 1144.02L64.90 1144.18L65.41 1144.25L65.91 1144.25L66.38 1144.18" fill="none" stroke="url(#gold)" stroke-width="1.6"/>
|
||||
<use href="#leaf" transform="translate(41.70 1112.20) rotate(164.97) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(35.99 1155.53) rotate(92.85) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(69.11 1171.23) rotate(20.21) scale(0.63)"/>
|
||||
<use href="#leaf" transform="translate(89.17 1149.42) rotate(-53.38) scale(0.48)"/>
|
||||
<circle cx="66.38" cy="1144.18" r="3.3" fill="#542f2e"/>
|
||||
<circle cx="66.38" cy="1144.18" r="1.5" fill="#e4c783"/>
|
||||
<use href="#leaf" transform="translate(95.32 976.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M95.32 976Q56.32 982 56.32 956" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(56.32 956.00) rotate(-25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(93.56 1068.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M93.56 1068Q132.56 1074 132.56 1048" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(132.56 1048.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(80.68 1096.00) rotate(56.00) scale(0.84)"/>
|
||||
<path d="M80.68 1096Q119.68 1102 119.68 1076" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(119.68 1076.00) rotate(25.00) scale(0.55)"/>
|
||||
<use href="#leaf" transform="translate(82.44 1188.00) rotate(-56.00) scale(0.84)"/>
|
||||
<path d="M82.44 1188Q43.44 1194 43.44 1168" fill="none" stroke="#c6a45f" stroke-width="0.8"/>
|
||||
<use href="#bud" transform="translate(43.44 1168.00) rotate(-25.00) scale(0.55)"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(0)"/>
|
||||
<circle cx="58.00" cy="1051.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(45)"/>
|
||||
<circle cx="54.19" cy="1060.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(90)"/>
|
||||
<circle cx="45.00" cy="1064.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(135)"/>
|
||||
<circle cx="35.81" cy="1060.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(180)"/>
|
||||
<circle cx="32.00" cy="1051.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(225)"/>
|
||||
<circle cx="35.81" cy="1041.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(270)"/>
|
||||
<circle cx="45.00" cy="1038.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(45 1051) rotate(315)"/>
|
||||
<circle cx="54.19" cy="1041.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="45.00" cy="1051.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="45.00" cy="1051.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M42 1066q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M48 1066q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(0)"/>
|
||||
<circle cx="152.00" cy="1171.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(45)"/>
|
||||
<circle cx="148.19" cy="1180.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(90)"/>
|
||||
<circle cx="139.00" cy="1184.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(135)"/>
|
||||
<circle cx="129.81" cy="1180.19" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(180)"/>
|
||||
<circle cx="126.00" cy="1171.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(225)"/>
|
||||
<circle cx="129.81" cy="1161.81" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(270)"/>
|
||||
<circle cx="139.00" cy="1158.00" r="0.65" fill="#c6a45f"/>
|
||||
<ellipse cx="0" cy="-5" rx="2.4" ry="5" fill="url(#red)" stroke="#c6a45f" stroke-width=".5" transform="translate(139 1171) rotate(315)"/>
|
||||
<circle cx="148.19" cy="1161.81" r="0.65" fill="#c6a45f"/>
|
||||
<circle cx="139.00" cy="1171.00" r="3.2" fill="#d7b66e"/>
|
||||
<circle cx="139.00" cy="1171.00" r="1.1" fill="#f5e0ac"/>
|
||||
<path d="M136 1186q-12 10 -6 20q5 5 7-1q0-4 -4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<path d="M142 1186q12 10 6 20q-5 5 -7-1q0-4 4-2" fill="none" stroke="#c6a45f" stroke-width="0.55"/>
|
||||
<circle cx="158.00" cy="960.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="970.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="980.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="990.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="1000.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="1010.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="1020.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="1030.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="1040.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="1050.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="1060.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="1070.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="1080.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="1090.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="1100.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="163.00" cy="1110.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="162.33" cy="1120.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="160.50" cy="1130.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="158.00" cy="1140.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="1150.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="1160.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="153.00" cy="1170.00" r="1.1" fill="#a58951"/>
|
||||
<circle cx="153.67" cy="1180.00" r="0.7" fill="#a58951"/>
|
||||
<circle cx="155.50" cy="1190.00" r="0.7" fill="#a58951"/>
|
||||
<path d="M151 975V985M147 980H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<path d="M151 1095V1105M147 1100H155" fill="none" stroke="#c6a45f" stroke-width="0.7"/>
|
||||
<use href="#raptor" transform="translate(92.00 120.00) rotate(0.00) scale(0.92)"/>
|
||||
<circle cx="137.00" cy="120.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="130.97" cy="142.50" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="114.50" cy="158.97" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="92.00" cy="165.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="69.50" cy="158.97" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="53.03" cy="142.50" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="47.00" cy="120.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="53.03" cy="97.50" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="69.50" cy="81.03" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="92.00" cy="75.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="114.50" cy="81.03" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="130.97" cy="97.50" r="1.1" fill="#e4c783"/>
|
||||
<use href="#raptor" transform="translate(92.00 600.00) rotate(0.00) scale(0.92)"/>
|
||||
<circle cx="137.00" cy="600.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="130.97" cy="622.50" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="114.50" cy="638.97" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="92.00" cy="645.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="69.50" cy="638.97" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="53.03" cy="622.50" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="47.00" cy="600.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="53.03" cy="577.50" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="69.50" cy="561.03" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="92.00" cy="555.00" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="114.50" cy="561.03" r="1.1" fill="#e4c783"/>
|
||||
<circle cx="130.97" cy="577.50" r="1.1" fill="#e4c783"/>
|
||||
</g></svg>
|
||||
|
Before Width: | Height: | Size: 86 KiB |
@@ -1,50 +0,0 @@
|
||||
"""Regression checks for the reference coverage guard."""
|
||||
|
||||
import unittest
|
||||
|
||||
from check_reference import REFERENCE, check, operation_names
|
||||
|
||||
|
||||
class ReferenceCheckTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.document = REFERENCE.read_text()
|
||||
|
||||
def test_current_reference(self):
|
||||
self.assertEqual(check(self.document), [])
|
||||
|
||||
def test_missing_operation(self):
|
||||
document = self.document.replace('<article id="spat.graph_compute">', '<section>')
|
||||
self.assertIn("Missing operation: spat.graph_compute", check(document))
|
||||
|
||||
def test_duplicate_id(self):
|
||||
document = self.document + '<div id="spat.graph_compute"></div>'
|
||||
self.assertIn("Duplicate HTML id: spat.graph_compute", check(document))
|
||||
|
||||
def test_empty_semantics(self):
|
||||
prefix, marker, article = self.document.partition('<article id="spat.graph_compute">')
|
||||
document = prefix + marker + article.replace('data-field="semantics"', 'data-unused="semantics"', 1)
|
||||
self.assertIn("spat.graph_compute: missing/empty semantics", check(document))
|
||||
|
||||
def test_broken_links(self):
|
||||
errors = check(self.document + '<a href="#missing">bad</a><a href="missing.cpp">bad</a>')
|
||||
self.assertIn("Broken fragment: #missing", errors)
|
||||
self.assertIn("Broken local link: missing.cpp", errors)
|
||||
|
||||
def test_stale_operation(self):
|
||||
document = self.document.replace('id="spat.graph_compute"', 'id="spat.removed"')
|
||||
self.assertIn("Unknown/stale operation: spat.removed", check(document))
|
||||
|
||||
def test_inherited_operation_definitions(self):
|
||||
source = '''
|
||||
class Plan<string mnemonic> : SpatOp<mnemonic>;
|
||||
class Compute<string mnemonic> : Plan<mnemonic>;
|
||||
def Example : Compute<"example">;
|
||||
def LayoutAttr : EnumAttr<SpatialDialect, Layout, "layout">;
|
||||
// def Removed : SpatOp<"removed">;
|
||||
'''
|
||||
self.assertEqual(operation_names([source]), {"spat.example"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,107 +0,0 @@
|
||||
"""Check reference navigation and parse examples with the release compiler."""
|
||||
|
||||
from html.parser import HTMLParser
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
from check_reference import REFERENCE, ROOT, ReferenceParser
|
||||
|
||||
|
||||
OPT = ROOT / "build_release/Release/bin/onnx-mlir-opt"
|
||||
|
||||
|
||||
class IntroductionParser(HTMLParser):
|
||||
def __init__(self, document):
|
||||
super().__init__()
|
||||
self.examples = {}
|
||||
self.current = None
|
||||
self.contents = []
|
||||
self.in_contents = False
|
||||
self.feed(document)
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
attrs = dict(attrs)
|
||||
if tag == "pre" and "data-example" in attrs:
|
||||
self.current = attrs["data-example"]
|
||||
self.examples[self.current] = ""
|
||||
if tag == "nav":
|
||||
self.in_contents = attrs.get("aria-label") == "Table of contents"
|
||||
if self.in_contents and tag == "a":
|
||||
self.contents.append(attrs["href"])
|
||||
|
||||
def handle_data(self, data):
|
||||
if self.current:
|
||||
self.examples[self.current] += data
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "pre":
|
||||
self.current = None
|
||||
if tag == "nav":
|
||||
self.in_contents = False
|
||||
|
||||
|
||||
class IntroductionTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.document = REFERENCE.read_text()
|
||||
cls.introduction = IntroductionParser(cls.document)
|
||||
|
||||
def test_contents_covers_topics_and_indexes(self):
|
||||
self.assertLess(
|
||||
self.document.index('aria-label="Table of contents"'),
|
||||
self.document.index('<section id="reading">'),
|
||||
)
|
||||
parser = ReferenceParser()
|
||||
parser.feed(self.document)
|
||||
for target in self.introduction.contents:
|
||||
self.assertIn(target[1:], parser.ids)
|
||||
self.assertEqual(set(self.introduction.contents), {
|
||||
"#reading", "#compact", "#planning", "#compute-regions",
|
||||
"#graph-batches", "#input-representations", "#scheduling",
|
||||
"#destinations", "#memory-units", "#communication", "#contracts",
|
||||
"#spatial-index", "#pim-index",
|
||||
})
|
||||
|
||||
@unittest.skipUnless(OPT.is_file(), "Release onnx-mlir-opt is unavailable")
|
||||
def test_examples_parse_and_print(self):
|
||||
arguments = {
|
||||
"addition": "%a: tensor<1x4xf32>, %b: tensor<1x4xf32>",
|
||||
"rows": "%matrix: tensor<2x4xf32>",
|
||||
"plan": "%a: tensor<1x2x3x4xf32>, %b: tensor<1x2x3x4xf32>",
|
||||
"weighted": "%x: tensor<1x4xf32>",
|
||||
"graph-batch": "%x: tensor<1x8xf32>",
|
||||
"reconstruction": "%fragments: tensor<2x1x4xf32>",
|
||||
"core-batch": None,
|
||||
"destination": "%x: tensor<1x4xf32>, %dst: tensor<1x4xf32>",
|
||||
"bufferized": "%x: memref<1x4xf32>, %dst: memref<1x4xf32>",
|
||||
"copy": "%dst: memref<1x4xf32>, %src: memref<1x4xf32>",
|
||||
"gather": "%dst: memref<1x4xf32>, %src: memref<1x8xf32>",
|
||||
"send": "%x: tensor<1x4xf32>, %target: index",
|
||||
"receive": "%dst: tensor<1x4xf32>, %source: index",
|
||||
"signal": "%target: index, %event: index",
|
||||
"wait": "%event: index, %count: index",
|
||||
"deferred-group": "%a: tensor<1x4xf32>, %b: tensor<1x4xf32>",
|
||||
}
|
||||
self.assertEqual(set(self.introduction.examples), set(arguments))
|
||||
for name, args in arguments.items():
|
||||
with self.subTest(example=name):
|
||||
snippet = self.introduction.examples[name]
|
||||
if name in {"gather", "receive"}:
|
||||
snippet = "%zero = arith.constant 0 : index\n" + snippet
|
||||
if args is not None:
|
||||
snippet = f"func.func @example({args}) {{\n{snippet}\nreturn\n}}"
|
||||
program = f"module {{\n{snippet}\n}}\n"
|
||||
command = [str(OPT), "--maccel=PIM"]
|
||||
if name == "deferred-group":
|
||||
command.append("--mlir-print-op-generic")
|
||||
for _ in range(2):
|
||||
result = subprocess.run(
|
||||
command, input=program,
|
||||
text=True, capture_output=True, timeout=30,
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
program = result.stdout
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,104 +0,0 @@
|
||||
# Evaluation methodology
|
||||
|
||||
The [documentation index](../README.md) links execution guides, model provenance,
|
||||
reproduction details, and correctness experiments.
|
||||
|
||||
## Canonical result datasets and output roots
|
||||
|
||||
The authoritative default aggregate CSVs are:
|
||||
|
||||
- [Comparison results](../../validation/tools/pim/pimcomp/compare/results_comparison.csv)
|
||||
- [Ablation results](../../validation/tools/pim/ablation/results_ablation.csv)
|
||||
|
||||
They are intentionally checked in beside their scripts. Default benchmark runs
|
||||
update the corresponding canonical CSV; default plotting reads its current
|
||||
contents. Plot generation does not run benchmarks or establish publication
|
||||
provenance. Preserve the model/configuration/source/build revisions, invocation,
|
||||
reference inputs, and original per-case reports when publishing measurements.
|
||||
|
||||
An explicit custom `--out-dir PATH` keeps aggregate CSVs under that experiment
|
||||
root. Model artifacts still default to `validation/networks/pimcomp_models`;
|
||||
changing aggregate placement does not change artifact or shared-reference paths.
|
||||
Per-variant ablation summaries remain `<artifact-root>/ablation/<variant>/results_comparison.csv`.
|
||||
Use `--input PATH` to plot a custom aggregate. Plot destinations can be selected
|
||||
with `--output-dir PATH`. Cleanup of default model artifacts preserves the two
|
||||
canonical datasets.
|
||||
|
||||
## Functional validity and performance availability
|
||||
|
||||
Functional PASS/FAIL and performance availability are independent. A numerically
|
||||
correct program can fail performance simulation or complete no inference before
|
||||
the deadline. Missing, failed, skipped, unsupported, nonfinite, or nonpositive
|
||||
per-inference measurements become `NA` in aggregates, not zero. With zero
|
||||
completed outputs, interval, throughput, and energy per inference are unavailable;
|
||||
measured average chip power can still be reported. Functional status is retained.
|
||||
|
||||
Floating-point correctness requires both elementwise absolute/relative tolerance
|
||||
and a relative L2 limit for each nonzero reference output. The L2 limit prevents
|
||||
small reference outputs from accepting all-zero results under the absolute floor.
|
||||
It cannot substitute for the elementwise check. Zero references use the absolute
|
||||
check; integer outputs require exact agreement. Nonfinite outputs are rejected.
|
||||
Validation reports record both maximum absolute and relative L2 errors.
|
||||
Report reuse includes the validation-policy identity.
|
||||
|
||||
Removing normalization operations can amplify floating-point sensitivity and
|
||||
change the computation. Such variants must use their own native reference.
|
||||
Agreement in a global norm alone does not establish elementwise correctness.
|
||||
Independent reference implementations and higher-precision calculations can
|
||||
help diagnose rounding sensitivity without relaxing the recorded pass criteria.
|
||||
|
||||
Ablation percentages require positive finite values for both the variant and
|
||||
its matching baseline. Tiny positive measurements retain significant digits
|
||||
instead of being rounded to zero in the comparison CSV. An extreme valid
|
||||
decrease can round to `-100.00%`; that value alone is not evidence of failure.
|
||||
Reciprocal output interval and throughput cannot both have that decrease.
|
||||
The ablation report uses each disabled feature as its comparison baseline.
|
||||
Planning gain uses `no-plan`; throughput synchronization gain uses `no-sync`.
|
||||
Throughput gain measures the relative increase. Latency, power, and energy gains
|
||||
measure relative reductions. Both programs' functional statuses remain separate.
|
||||
|
||||
## Report reuse and implementation revisions
|
||||
|
||||
The [comparison guide](../../validation/tools/pim/pimcomp/compare/README.md)
|
||||
describes fingerprint validation and failed-report reuse. Fingerprints cover
|
||||
model/configuration contents and experiment settings, but do not identify
|
||||
compiler/tool implementations, built binaries, or manually changed reference
|
||||
artifacts. Reuse is not proof of unchanged tool behavior: rerun the relevant
|
||||
compiler after those change, and record build/source revisions for publication.
|
||||
No revision cache is inferred from Git HEAD, which would miss dirty sources,
|
||||
external tools, and binaries built from another checkout.
|
||||
|
||||
## Metric interpretation
|
||||
|
||||
Metrics come from Pimsim's
|
||||
[`Chip::getSimulationReport`](../../backend-simulators/pim/pimsim-nn/src/chip/Chip.cpp)
|
||||
and [`EnergyCounter`](../../backend-simulators/pim/pimsim-nn/src/utils/EnergyCounter.cpp).
|
||||
|
||||
Pimsim-nn omits `vsoftmax` before instruction fetch. Reported performance and
|
||||
energy exclude its work. The PIM queue estimator uses the same omission.
|
||||
Functional validation executes Softmax and compares the same full model with
|
||||
its native reference. This timing approximation does not establish hardware
|
||||
support for Softmax or include its execution energy.
|
||||
|
||||
- Latency mode measures time to complete one inference.
|
||||
- Throughput-mode latency is measurement duration / completed iterations,
|
||||
equal to `1000 / throughput` before rounding. It is not end-to-end pipelined
|
||||
inference latency; multiplying it by depth does not establish that quantity.
|
||||
- Average power is total modeled static + dynamic chip energy / elapsed time.
|
||||
- Energy per inference is total energy / completed iterations (one in latency
|
||||
mode). Plots convert pJ to mJ with `1e-9`; no pipeline-depth or batch-size
|
||||
division is applied.
|
||||
|
||||
Existing `average_energy_pj`, `raptor_energy_pj`, and validation CSV energy
|
||||
columns retain their names for compatibility. They contain energy per inference.
|
||||
|
||||
Fast mode measures throughput over the last two convergence windows but power
|
||||
and energy over the entire run up to early stop. Energy includes startup and
|
||||
work in flight, so it need not equal average power / reported throughput.
|
||||
If convergence fails, comparison and ablation reports retain the simulator's
|
||||
full-duration fallback throughput. This measurement includes transient execution.
|
||||
It does not establish steady-state convergence. The per-case JSON records its
|
||||
measurement type and convergence status. Missing or invalid measurements remain `NA`.
|
||||
Use `--no-fast` for full-duration measurements. Consult the
|
||||
[correctness notes](../../validation/tools/pim/pimcomp/correctness/README.md) before interpreting failed rows
|
||||
as performance comparisons.
|
||||
@@ -1,114 +0,0 @@
|
||||
# Pimcomp reproduction reference
|
||||
|
||||
The [model README](../../validation/networks/pimcomp_models/README.md) owns provenance, checksums, hardware profiles, and
|
||||
numeric-artifact limitations. The [comparison guide](../../validation/tools/pim/pimcomp/compare/README.md)
|
||||
owns suite commands, reports, reuse rules, and metric interpretation.
|
||||
|
||||
## Frontend acceptance versus scheduled computation
|
||||
|
||||
The current [frontend mapping](../../third_party/PIMCOMP-NN/frontend/frontend.py)
|
||||
accepts exactly these ONNX node types:
|
||||
|
||||
```text
|
||||
Add, AveragePool, BatchNormalization, Clip, Concat, Conv, Dropout, Flatten,
|
||||
Gather, Gemm, GlobalAveragePool, LRN, MatMul, MaxPool, Mul, Pad, Relu, Reshape,
|
||||
Shape, Sigmoid, Softmax, Squeeze, Sub, Sum, Tanh, Transpose, Unsqueeze
|
||||
```
|
||||
|
||||
`Constant` is consumed as metadata rather than emitted as a backend node.
|
||||
Other types cause `operation: <type> not considered` and stop conversion at
|
||||
the first occurrence. In particular, YOLO11n's Split and Resize are unsupported;
|
||||
the emitted prefix cannot represent a complete inference.
|
||||
|
||||
The latency scheduler's explicit no-consider set, also used by hierarchy
|
||||
mapping and GA post-operation accounting, is:
|
||||
|
||||
```text
|
||||
Input, BatchNormalization, Clip, Dropout, Flatten, LRN, MatMul, Reshape,
|
||||
Softmax, Squeeze, Transpose
|
||||
```
|
||||
|
||||
See [ElementPipelineSchedule.cpp](../../third_party/PIMCOMP-NN/backend/ElementPipelineSchedule.cpp),
|
||||
[HierarchyMapping.cpp](../../third_party/PIMCOMP-NN/backend/HierarchyMapping.cpp),
|
||||
and [GeneticAlgorithm.cpp](../../third_party/PIMCOMP-NN/backend/GeneticAlgorithm.cpp).
|
||||
These accepted nodes receive no standalone latency instructions while remaining
|
||||
in the backend graph. Acceptance therefore does not establish timed computation.
|
||||
|
||||
Before scheduling, the frontend may fuse BatchNorm/Relu/Tanh/Sigmoid into
|
||||
Conv/Gemm, turn Reshape–Transpose–Reshape into channel shuffle, remove a specific
|
||||
Shape–Gather–Unsqueeze–Concat shape chain, and merge Pad into its consumer.
|
||||
Those transformations differ from both frontend rejection and leaving a node
|
||||
unscheduled. In particular, the [BatchNorm correctness gap](../../validation/tools/pim/pimcomp/correctness/README.md#resnet-batchnorm-gap)
|
||||
shows why a fusion label is not proof of numeric equivalence.
|
||||
|
||||
Pimsim accepts ISA instructions rather than ONNX operators. Its
|
||||
[instruction decoder](../../backend-simulators/pim/pimsim-nn/src/isa/Instruction.cpp)
|
||||
omits `vsoftmax` (binary opcode 21) before fetch and warns once per process
|
||||
because it has no timing model. Other unknown opcodes remain errors.
|
||||
Reported timing and energy exclude Softmax work. Functional validation still
|
||||
executes Softmax. The comparison uses full YOLO and GoogLeNet with only its two
|
||||
LRN nodes bypassed. VGG8 and both ResNet graphs retain all operators.
|
||||
The historical `*-pimsim-nn.onnx` files retain the earlier Softmax-free graphs
|
||||
for result reproduction; they are no longer the suite's selected inputs.
|
||||
|
||||
## Standalone frontend/backend reproduction
|
||||
|
||||
Build Pimcomp with CMake and an OpenMP-capable C++ compiler:
|
||||
|
||||
```bash
|
||||
cmake -S third_party/PIMCOMP-NN -B third_party/PIMCOMP-NN/build
|
||||
cmake --build third_party/PIMCOMP-NN/build --target PIMCOMP-NN
|
||||
```
|
||||
|
||||
The backend resolves `../config.json`, `../models/JSON/<name>.json`, and
|
||||
`../output/` relative to its working directory, not its executable. The frontend
|
||||
rewrites its input ONNX batch dimension in place. Use an isolated workspace and
|
||||
a model copy, as the comparison driver does, to preserve source/config files.
|
||||
From the Raptor root, after installing the [frontend dependencies](../../third_party/PIMCOMP-NN/README.md):
|
||||
|
||||
```bash
|
||||
RAPTOR_ROOT=$PWD
|
||||
PIMCOMP="$RAPTOR_ROOT/third_party/PIMCOMP-NN"
|
||||
PIMCOMP_RUN=$(mktemp -d)
|
||||
mkdir -p "$PIMCOMP_RUN/models/JSON" "$PIMCOMP_RUN/output" "$PIMCOMP_RUN/work"
|
||||
cp validation/pimsim_configs/pimcomp/arch-a/latency_config.json "$PIMCOMP_RUN/config.json"
|
||||
cp validation/networks/pimcomp_models/vgg8/vgg8-mnist-reconstructed.onnx "$PIMCOMP_RUN/vgg8.onnx"
|
||||
.venv/bin/python "$PIMCOMP/frontend/frontend.py" \
|
||||
--model_path "$PIMCOMP_RUN/vgg8.onnx" \
|
||||
--save_path "$PIMCOMP_RUN/models/JSON/vgg8.json"
|
||||
(
|
||||
cd "$PIMCOMP_RUN/work"
|
||||
OMP_NUM_THREADS=1 "$PIMCOMP/build/PIMCOMP-NN" \
|
||||
-m=vgg8 -r=GA -p=element -o=YES -v=YES -s=YES
|
||||
)
|
||||
```
|
||||
|
||||
Outputs remain under `$PIMCOMP_RUN/output`. `-v=YES` emits verification data;
|
||||
`-s=YES` emits `SimulationInfo.gz`; `-o=YES` saves the evaluation report.
|
||||
Use `-p=batch` for throughput scheduling, with the matching throughput config
|
||||
when running Pimsim. The paper's batch experiment used 128 samples; the current
|
||||
comparison runner's functional batch default is 64. Element mode represents one
|
||||
inference. Select Arch-B/C by copying that profile's config; Arch-C's rectangular
|
||||
crossbars remain unsupported by Raptor.
|
||||
|
||||
For the bundled Model Zoo graphs, copy `models/JSON/resnet18.json`,
|
||||
`resnet34.json`, or `googlenet.json` from Pimcomp to the workspace and change
|
||||
`-m` accordingly. That reproduces bundled graph scheduling; use the suite
|
||||
runner to regenerate graphs from the exact checked-in performance ONNX files.
|
||||
|
||||
## Genetic algorithm and reproducibility limits
|
||||
|
||||
[`GeneticAlgorithm.h`](../../third_party/PIMCOMP-NN/backend/GeneticAlgorithm.h)
|
||||
sets population 200 and at most 1000 iterations. `-r=GA` selects it; standalone
|
||||
backend default replication is `balance`, whereas the suite explicitly uses GA.
|
||||
GA initialization calls `srand(1)`. Fitness evaluation uses OpenMP with static
|
||||
work distribution; `OMP_NUM_THREADS` bounds its parallelism (use 1 for serial
|
||||
reproduction), otherwise the OpenMP runtime chooses the thread count.
|
||||
|
||||
The fixed GA seed does not make every backend stage deterministic:
|
||||
`ElementPipelineSchedule.cpp` separately calls `srand(time(NULL))`. Keep model
|
||||
hashes, source/build revisions, profile, mode, and thread count with experiment
|
||||
results. Compare correctness
|
||||
against the original ONNX reference, including the known batch and BatchNorm
|
||||
failures; neither omitted operators nor prefilled reference intermediates repair
|
||||
those programs.
|
||||
@@ -1,5 +1,4 @@
|
||||
colorama>=0.4.6,<1
|
||||
matplotlib>=3.8,<4
|
||||
numpy>=1.26.4,<3
|
||||
onnx>=1.17,<2
|
||||
onnxsim>=0.6.5,<1
|
||||
|
||||
@@ -94,7 +94,7 @@ endfunction()
|
||||
|
||||
add_subdirectory(Dialect)
|
||||
add_subdirectory(Common)
|
||||
add_subdirectory(Passes)
|
||||
add_subdirectory(Pass)
|
||||
add_subdirectory(Compiler)
|
||||
add_subdirectory(Conversion)
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ add_pim_library(OMPimCommon
|
||||
IR/AddressAnalysis.cpp
|
||||
IR/BatchCoreUtils.cpp
|
||||
IR/ConstantUtils.cpp
|
||||
IR/CopyAccessPlan.cpp
|
||||
IR/CoreBlockUtils.cpp
|
||||
IR/EntryPointUtils.cpp
|
||||
IR/IndexingUtils.cpp
|
||||
|
||||
@@ -171,9 +171,7 @@ static llvm::FailureOr<int64_t> resolveConstantGlobalLoad(mlir::memref::LoadOp l
|
||||
if (indices.size() != static_cast<size_t>(globalType.getRank()))
|
||||
return mlir::failure();
|
||||
|
||||
auto checkedStrides = computeRowMajorStridesChecked(globalType.getShape());
|
||||
if (failed(checkedStrides)) return mlir::failure();
|
||||
auto strides = std::move(*checkedStrides);
|
||||
auto strides = computeRowMajorStrides(globalType.getShape());
|
||||
int64_t linearIndex = linearizeIndex(indices, strides);
|
||||
if (linearIndex < 0 || linearIndex >= globalType.getNumElements())
|
||||
return mlir::failure();
|
||||
@@ -310,9 +308,7 @@ llvm::FailureOr<CompiledIndexExpr> compileConstantGlobalLoad(mlir::memref::LoadO
|
||||
CompiledIndexExprNode expr;
|
||||
expr.kind = CompiledIndexExprNode::Kind::ConstantGlobalLoad;
|
||||
expr.globalOp = globalOp;
|
||||
auto checkedStrides = computeRowMajorStridesChecked(globalType.getShape());
|
||||
if (failed(checkedStrides)) return mlir::failure();
|
||||
expr.globalStrides = std::move(*checkedStrides);
|
||||
expr.globalStrides = computeRowMajorStrides(globalType.getShape());
|
||||
expr.operands.reserve(loadOp.getIndices().size());
|
||||
for (mlir::Value index : loadOp.getIndices()) {
|
||||
auto compiledIndex = compileIndexValueImpl(index);
|
||||
|
||||
@@ -19,7 +19,7 @@ struct ResolvedContiguousAddress {
|
||||
};
|
||||
|
||||
/// Records compile-time facts used when interpreting address arithmetic and
|
||||
/// loop-carried aliases inside Pim regions.
|
||||
/// loop-carried aliases inside PIM regions.
|
||||
struct StaticValueKnowledge {
|
||||
llvm::DenseMap<mlir::Value, int64_t> indexValues;
|
||||
llvm::DenseMap<mlir::Value, mlir::Value> aliases;
|
||||
|
||||
@@ -10,18 +10,6 @@ using namespace mlir;
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
bool isZeroBitPatternSplat(Attribute value) {
|
||||
auto dense = dyn_cast_or_null<DenseElementsAttr>(value);
|
||||
if (!dense || !dense.isSplat())
|
||||
return false;
|
||||
Attribute element = dense.getSplatValue<Attribute>();
|
||||
if (auto floating = dyn_cast<FloatAttr>(element))
|
||||
return floating.getValue().isZero() && !floating.getValue().isNegative();
|
||||
if (auto integer = dyn_cast<IntegerAttr>(element))
|
||||
return integer.getValue().isZero();
|
||||
return false;
|
||||
}
|
||||
|
||||
ConstantPool::ConstantPool(Operation *constantAnchor, OpBuilder &builder)
|
||||
: anchor(constantAnchor), block(getConstantInsertionBlock(constantAnchor)),
|
||||
builder(builder) {
|
||||
|
||||
@@ -12,9 +12,6 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
// Negative floating zero has a distinct representation and must not match.
|
||||
bool isZeroBitPatternSplat(mlir::Attribute value);
|
||||
|
||||
class ConstantPool {
|
||||
public:
|
||||
ConstantPool(mlir::Operation *constantAnchor, mlir::OpBuilder &builder);
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
#include "CopyAccessPlan.hpp"
|
||||
#include "llvm/ADT/STLExtras.h"
|
||||
#include "llvm/Support/CheckedArithmetic.h"
|
||||
#include <algorithm>
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
mlir::FailureOr<int64_t> getContiguousSuffixRank(
|
||||
llvm::ArrayRef<int64_t> shape, llvm::ArrayRef<int64_t> elementStrides) {
|
||||
if (shape.size() != elementStrides.size()
|
||||
|| llvm::any_of(shape, [](int64_t size) { return size <= 0; }))
|
||||
return mlir::failure();
|
||||
int64_t expectedStride = 1, rank = 0;
|
||||
for (size_t dim = shape.size(); dim-- > 0;) {
|
||||
if (shape[dim] != 1 && elementStrides[dim] != expectedStride)
|
||||
break;
|
||||
++rank;
|
||||
auto next = llvm::checkedMul(expectedStride, shape[dim]);
|
||||
if (!next) return mlir::failure();
|
||||
expectedStride = *next;
|
||||
}
|
||||
return rank;
|
||||
}
|
||||
|
||||
mlir::FailureOr<CopyAccessPlan> CopyAccessPlan::build(
|
||||
llvm::ArrayRef<int64_t> shape, llvm::ArrayRef<int64_t> sourceElementStrides,
|
||||
llvm::ArrayRef<int64_t> targetElementStrides) {
|
||||
auto sourceSuffix = getContiguousSuffixRank(shape, sourceElementStrides);
|
||||
auto targetSuffix = getContiguousSuffixRank(shape, targetElementStrides);
|
||||
if (mlir::failed(sourceSuffix) || mlir::failed(targetSuffix))
|
||||
return mlir::failure();
|
||||
size_t outerRank = shape.size() - std::min(*sourceSuffix, *targetSuffix);
|
||||
CopyAccessPlan plan;
|
||||
plan.outerShape.assign(shape.begin(), shape.begin() + outerRank);
|
||||
plan.sourceOuterStrides.assign(sourceElementStrides.begin(), sourceElementStrides.begin() + outerRank);
|
||||
plan.targetOuterStrides.assign(targetElementStrides.begin(), targetElementStrides.begin() + outerRank);
|
||||
int64_t elements = 1, maximumSource = 0, maximumTarget = 0;
|
||||
for (size_t dim = 0; dim < shape.size(); ++dim) {
|
||||
if (dim < outerRank && (sourceElementStrides[dim] < 0 || targetElementStrides[dim] < 0))
|
||||
return mlir::failure();
|
||||
int64_t &product = dim < outerRank ? plan.runCount : plan.runElements;
|
||||
auto next = llvm::checkedMul(product, shape[dim]);
|
||||
auto total = llvm::checkedMul(elements, shape[dim]);
|
||||
if (!next || !total) return mlir::failure();
|
||||
product = *next;
|
||||
elements = *total;
|
||||
// Unit dimensions never access their stride, including negative strides.
|
||||
if (shape[dim] != 1) {
|
||||
auto sourceEnd = llvm::checkedMulAdd(shape[dim] - 1, sourceElementStrides[dim], maximumSource);
|
||||
auto targetEnd = llvm::checkedMulAdd(shape[dim] - 1, targetElementStrides[dim], maximumTarget);
|
||||
if (!sourceEnd || !targetEnd) return mlir::failure();
|
||||
maximumSource = *sourceEnd;
|
||||
maximumTarget = *targetEnd;
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
mlir::FailureOr<std::pair<int64_t, int64_t>> CopyAccessPlan::getRunOffsets(int64_t run) const {
|
||||
if (run < 0 || run >= runCount) return mlir::failure();
|
||||
int64_t source = 0, target = 0;
|
||||
for (size_t dim = outerShape.size(); dim-- > 0;) {
|
||||
int64_t coordinate = run % outerShape[dim];
|
||||
run /= outerShape[dim];
|
||||
auto nextSource = llvm::checkedMulAdd(coordinate, sourceOuterStrides[dim], source);
|
||||
auto nextTarget = llvm::checkedMulAdd(coordinate, targetOuterStrides[dim], target);
|
||||
if (!nextSource || !nextTarget) return mlir::failure();
|
||||
source = *nextSource;
|
||||
target = *nextTarget;
|
||||
}
|
||||
return std::pair{source, target};
|
||||
}
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,37 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "mlir/Support/LogicalResult.h"
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include <cstdint>
|
||||
#include <utility>
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
// Geometry only. Callers must prove storage layout, aliasing, and copy legality.
|
||||
mlir::FailureOr<int64_t> getContiguousSuffixRank(
|
||||
llvm::ArrayRef<int64_t> shape, llvm::ArrayRef<int64_t> elementStrides);
|
||||
|
||||
class CopyAccessPlan {
|
||||
public:
|
||||
// All accessed relative element offsets must fit int64_t, including run tails.
|
||||
// Byte scaling and addition of base addresses remain caller responsibilities.
|
||||
static mlir::FailureOr<CopyAccessPlan> build(llvm::ArrayRef<int64_t> shape,
|
||||
llvm::ArrayRef<int64_t> sourceElementStrides,
|
||||
llvm::ArrayRef<int64_t> targetElementStrides);
|
||||
|
||||
int64_t getRunCount() const { return runCount; }
|
||||
int64_t getRunElements() const { return runElements; }
|
||||
llvm::ArrayRef<int64_t> getOuterShape() const { return outerShape; }
|
||||
llvm::ArrayRef<int64_t> getSourceOuterStrides() const { return sourceOuterStrides; }
|
||||
llvm::ArrayRef<int64_t> getTargetOuterStrides() const { return targetOuterStrides; }
|
||||
// Source and target element offsets, relative to their separately proven bases.
|
||||
mlir::FailureOr<std::pair<int64_t, int64_t>> getRunOffsets(int64_t run) const;
|
||||
|
||||
private:
|
||||
int64_t runCount = 1;
|
||||
int64_t runElements = 1;
|
||||
llvm::SmallVector<int64_t> outerShape, sourceOuterStrides, targetOuterStrides;
|
||||
};
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -85,12 +85,12 @@ static mlir::LogicalResult walkPimCoreBlockImpl(mlir::Block& block,
|
||||
auto step = resolveIndexValue(forOp.getStep(), knowledge);
|
||||
if (failed(lower) || failed(upper) || failed(step)
|
||||
|| (mode == CoreWalkMode::ExecuteCommunication && *step <= 0)) {
|
||||
forOp.emitOpError() << "requires statically evaluable scf.for bounds for Pim " << purpose;
|
||||
forOp.emitOpError() << "requires statically evaluable scf.for bounds for PIM " << purpose;
|
||||
hasFailure = true;
|
||||
continue;
|
||||
}
|
||||
if (*step <= 0) {
|
||||
forOp.emitOpError("requires positive scf.for step for Pim verification");
|
||||
forOp.emitOpError("requires positive scf.for step for PIM verification");
|
||||
hasFailure = true;
|
||||
continue;
|
||||
}
|
||||
@@ -126,7 +126,7 @@ static mlir::LogicalResult walkPimCoreBlockImpl(mlir::Block& block,
|
||||
if (auto ifOp = mlir::dyn_cast<mlir::scf::IfOp>(op)) {
|
||||
auto condition = resolveIndexValue(ifOp.getCondition(), knowledge);
|
||||
if (failed(condition)) {
|
||||
ifOp.emitOpError() << "requires statically evaluable scf.if condition for Pim " << purpose;
|
||||
ifOp.emitOpError() << "requires statically evaluable scf.if condition for PIM " << purpose;
|
||||
hasFailure = true;
|
||||
continue;
|
||||
}
|
||||
@@ -147,7 +147,7 @@ static mlir::LogicalResult walkPimCoreBlockImpl(mlir::Block& block,
|
||||
if (auto switchOp = mlir::dyn_cast<mlir::scf::IndexSwitchOp>(op)) {
|
||||
auto selector = resolveIndexValue(switchOp.getArg(), knowledge);
|
||||
if (failed(selector)) {
|
||||
switchOp.emitOpError() << "requires a statically evaluable scf.index_switch selector for Pim " << purpose;
|
||||
switchOp.emitOpError() << "requires a statically evaluable scf.index_switch selector for PIM " << purpose;
|
||||
hasFailure = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace onnx_mlir {
|
||||
using PimCoreCommunicationPlan = llvm::DenseMap<mlir::Block*, llvm::SmallVector<mlir::Operation*, 8>>;
|
||||
|
||||
/// Returns true for ops in a `pim.core` body that only participate in static
|
||||
/// address or index computation and therefore do not emit Pim instructions.
|
||||
/// address or index computation and therefore do not emit PIM instructions.
|
||||
bool isCoreStaticAddressOp(mlir::Operation* op);
|
||||
|
||||
/// Walks a `pim.core` body's communication stream, statically unrolling
|
||||
|
||||
@@ -9,7 +9,7 @@ llvm::FailureOr<mlir::func::FuncOp> getPimEntryFunc(mlir::ModuleOp moduleOp) {
|
||||
|
||||
llvm::SmallVector<mlir::ONNXEntryPointOp> entryPoints(moduleOp.getOps<mlir::ONNXEntryPointOp>());
|
||||
if (entryPoints.size() > 1) {
|
||||
moduleOp.emitError("Pim pipeline requires a single ONNX entry point, but found ") << entryPoints.size();
|
||||
moduleOp.emitError("PIM pipeline requires a single ONNX entry point, but found ") << entryPoints.size();
|
||||
return mlir::failure();
|
||||
}
|
||||
if (!entryPoints.empty()) {
|
||||
@@ -38,7 +38,7 @@ llvm::FailureOr<mlir::func::FuncOp> getPimEntryFunc(mlir::ModuleOp moduleOp) {
|
||||
if (nonExternalFuncs.size() == 1)
|
||||
return nonExternalFuncs.front();
|
||||
|
||||
moduleOp.emitError("could not resolve a unique Pim entry function");
|
||||
moduleOp.emitError("could not resolve a unique PIM entry function");
|
||||
return mlir::failure();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
/// Resolves the function the Pim pipeline should treat as its entry point.
|
||||
/// Resolves the function the PIM pipeline should treat as its entry point.
|
||||
/// Prefers ONNX entry-point metadata, then `main_graph`, then the only
|
||||
/// non-external function if the module is otherwise unambiguous.
|
||||
llvm::FailureOr<mlir::func::FuncOp> getPimEntryFunc(mlir::ModuleOp moduleOp);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#include "llvm/ADT/STLExtras.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include "llvm/Support/CheckedArithmetic.h"
|
||||
|
||||
#include <functional>
|
||||
|
||||
@@ -10,42 +9,12 @@
|
||||
namespace onnx_mlir {
|
||||
|
||||
llvm::SmallVector<int64_t> computeRowMajorStrides(llvm::ArrayRef<int64_t> shape) {
|
||||
auto strides = computeRowMajorStridesChecked(shape);
|
||||
if (mlir::failed(strides))
|
||||
llvm::report_fatal_error("row-major strides are not representable in int64_t");
|
||||
return std::move(*strides);
|
||||
}
|
||||
|
||||
mlir::FailureOr<llvm::SmallVector<int64_t>>
|
||||
computeRowMajorStridesChecked(llvm::ArrayRef<int64_t> shape) {
|
||||
llvm::SmallVector<int64_t> strides(shape.size(), 1);
|
||||
for (int64_t dim = static_cast<int64_t>(shape.size()) - 2; dim >= 0; --dim) {
|
||||
auto stride = llvm::checkedMul(strides[dim + 1], shape[dim + 1]);
|
||||
if (!stride) return mlir::failure();
|
||||
strides[dim] = *stride;
|
||||
}
|
||||
for (int64_t dim = static_cast<int64_t>(shape.size()) - 2; dim >= 0; --dim)
|
||||
strides[dim] = strides[dim + 1] * shape[dim + 1];
|
||||
return strides;
|
||||
}
|
||||
|
||||
TransposeRun getTransposeRun(llvm::ArrayRef<int64_t> sourceShape,
|
||||
llvm::ArrayRef<int64_t> permutation) {
|
||||
auto sourceStrides = computeRowMajorStrides(sourceShape);
|
||||
TransposeRun run{sourceShape.size(), 1, 1};
|
||||
for (size_t dim = permutation.size(); dim-- > 0;) {
|
||||
int64_t sourceDim = permutation[dim];
|
||||
if (sourceShape[sourceDim] == 1)
|
||||
continue;
|
||||
int64_t stride = sourceStrides[sourceDim];
|
||||
if (run.start != sourceShape.size() && stride != run.elements * run.sourceStride)
|
||||
break;
|
||||
run.start = dim;
|
||||
if (run.elements == 1)
|
||||
run.sourceStride = stride;
|
||||
run.elements *= sourceShape[sourceDim];
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
llvm::SmallVector<int64_t>
|
||||
delinearizeIndex(int64_t linearIndex, llvm::ArrayRef<int64_t> shape, llvm::ArrayRef<int64_t> strides) {
|
||||
llvm::SmallVector<int64_t> indices(shape.size(), 0);
|
||||
|
||||
@@ -19,20 +19,7 @@ namespace onnx_mlir {
|
||||
using HSliceId = size_t;
|
||||
using CoreId = size_t;
|
||||
|
||||
// Invariant form fails explicitly on overflow, including assertion-free builds.
|
||||
// Optional analyses and rewrites must use the checked form.
|
||||
llvm::SmallVector<int64_t> computeRowMajorStrides(llvm::ArrayRef<int64_t> shape);
|
||||
mlir::FailureOr<llvm::SmallVector<int64_t>>
|
||||
computeRowMajorStridesChecked(llvm::ArrayRef<int64_t> shape);
|
||||
|
||||
struct TransposeRun {
|
||||
size_t start;
|
||||
int64_t elements;
|
||||
int64_t sourceStride;
|
||||
};
|
||||
|
||||
TransposeRun getTransposeRun(llvm::ArrayRef<int64_t> sourceShape,
|
||||
llvm::ArrayRef<int64_t> permutation);
|
||||
|
||||
llvm::SmallVector<int64_t>
|
||||
delinearizeIndex(int64_t linearIndex, llvm::ArrayRef<int64_t> shape, llvm::ArrayRef<int64_t> strides);
|
||||
|
||||
@@ -191,9 +191,7 @@ resolveWeightView(mlir::Operation* coreLikeOp, mlir::Value weight, const StaticV
|
||||
ResolvedWeightView view;
|
||||
view.globalOp = globalOp;
|
||||
view.shape.assign(denseAttr.getType().getShape().begin(), denseAttr.getType().getShape().end());
|
||||
auto checkedStrides = computeRowMajorStridesChecked(view.shape);
|
||||
if (failed(checkedStrides)) return mlir::failure();
|
||||
view.strides = std::move(*checkedStrides);
|
||||
view.strides = computeRowMajorStrides(view.shape);
|
||||
|
||||
CompiledIndexExpr offsetExpr = makeConstantExpr(0);
|
||||
for (mlir::Operation* viewOp : llvm::reverse(viewOps)) {
|
||||
|
||||
@@ -32,7 +32,7 @@ struct ResolvedWeightView {
|
||||
bool hasWeightAlways(mlir::Operation* op);
|
||||
|
||||
/// Tags an op as producing a value that should stay materialized as a reusable
|
||||
/// weight across later Pim lowering/codegen stages.
|
||||
/// weight across later PIM lowering/codegen stages.
|
||||
void markWeightAlways(mlir::Operation* op);
|
||||
|
||||
bool isSpatialMvmVmmWeightUse(mlir::OpOperand& use);
|
||||
|
||||
@@ -32,9 +32,6 @@ inline constexpr llvm::StringLiteral kCoreIdAttrName = "coreId";
|
||||
inline constexpr llvm::StringLiteral kCoreIdsAttrName = "coreIds";
|
||||
inline constexpr llvm::StringLiteral kLocalMemoryAddressAttrName = "pim.local_memory_address";
|
||||
inline constexpr llvm::StringLiteral kLocalMemorySizeAttrName = "pim.local_memory_size";
|
||||
inline constexpr llvm::StringLiteral kPipelineHostBufferBytesAttrName = "pim.pipeline_host_buffer_bytes";
|
||||
inline constexpr llvm::StringLiteral kPipelineHostBufferName = "pim_pipeline_channels";
|
||||
inline constexpr size_t kPimEventRegisterCount = 32;
|
||||
inline constexpr std::array<llvm::StringLiteral, 4> kRemovedLocalMemoryPlanAttrNames = {
|
||||
"pim.local_memory_slot",
|
||||
"pim.local_memory_slot_size",
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace onnx_mlir::pim {
|
||||
namespace {
|
||||
|
||||
static void emitCrashMessage(llvm::StringRef fieldName, llvm::StringRef message) {
|
||||
llvm::errs() << "Pim " << fieldName << " " << message << "\n";
|
||||
llvm::errs() << "PIM " << fieldName << " " << message << "\n";
|
||||
}
|
||||
|
||||
template <typename To, typename From>
|
||||
@@ -65,7 +65,7 @@ InFlightDiagnostic emitCheckedArithmeticError(Operation* anchor, llvm::StringRef
|
||||
}
|
||||
|
||||
InFlightDiagnostic emitCheckedArithmeticError(Location loc, llvm::StringRef fieldName, llvm::StringRef message) {
|
||||
return emitError(loc) << "Pim " << fieldName << " " << message;
|
||||
return emitError(loc) << "PIM " << fieldName << " " << message;
|
||||
}
|
||||
|
||||
FailureOr<int32_t> checkedI32(int64_t value, Operation* anchor, llvm::StringRef fieldName) {
|
||||
@@ -174,7 +174,7 @@ FailureOr<uint64_t> getCheckedShapedTypeSizeInBytes(ShapedType type, Location lo
|
||||
int32_t checkedI32OrCrash(int64_t value, llvm::StringRef fieldName) {
|
||||
if (value < std::numeric_limits<int32_t>::min() || value > std::numeric_limits<int32_t>::max()) {
|
||||
emitCrashMessage(fieldName, "is outside representable range");
|
||||
llvm_unreachable("Pim checked arithmetic failure");
|
||||
llvm_unreachable("PIM checked arithmetic failure");
|
||||
}
|
||||
return static_cast<int32_t>(value);
|
||||
}
|
||||
@@ -182,7 +182,7 @@ int32_t checkedI32OrCrash(int64_t value, llvm::StringRef fieldName) {
|
||||
int32_t checkedI32OrCrash(uint64_t value, llvm::StringRef fieldName) {
|
||||
if (value > static_cast<uint64_t>(std::numeric_limits<int32_t>::max())) {
|
||||
emitCrashMessage(fieldName, "is outside representable range");
|
||||
llvm_unreachable("Pim checked arithmetic failure");
|
||||
llvm_unreachable("PIM checked arithmetic failure");
|
||||
}
|
||||
return static_cast<int32_t>(value);
|
||||
}
|
||||
@@ -190,7 +190,7 @@ int32_t checkedI32OrCrash(uint64_t value, llvm::StringRef fieldName) {
|
||||
uint8_t checkedU8OrCrash(uint64_t value, llvm::StringRef fieldName) {
|
||||
if (value > static_cast<uint64_t>(std::numeric_limits<uint8_t>::max())) {
|
||||
emitCrashMessage(fieldName, "is outside representable range");
|
||||
llvm_unreachable("Pim checked arithmetic failure");
|
||||
llvm_unreachable("PIM checked arithmetic failure");
|
||||
}
|
||||
return static_cast<uint8_t>(value);
|
||||
}
|
||||
@@ -198,7 +198,7 @@ uint8_t checkedU8OrCrash(uint64_t value, llvm::StringRef fieldName) {
|
||||
size_t checkedSizeOrCrash(int64_t value, llvm::StringRef fieldName) {
|
||||
if (value < 0) {
|
||||
emitCrashMessage(fieldName, "is outside representable range");
|
||||
llvm_unreachable("Pim checked arithmetic failure");
|
||||
llvm_unreachable("PIM checked arithmetic failure");
|
||||
}
|
||||
return static_cast<size_t>(value);
|
||||
}
|
||||
@@ -206,7 +206,7 @@ size_t checkedSizeOrCrash(int64_t value, llvm::StringRef fieldName) {
|
||||
size_t checkedAddOrCrash(size_t lhs, size_t rhs, llvm::StringRef fieldName) {
|
||||
if (rhs > std::numeric_limits<size_t>::max() - lhs) {
|
||||
emitCrashMessage(fieldName, "addition overflow");
|
||||
llvm_unreachable("Pim checked arithmetic failure");
|
||||
llvm_unreachable("PIM checked arithmetic failure");
|
||||
}
|
||||
return lhs + rhs;
|
||||
}
|
||||
@@ -214,7 +214,7 @@ size_t checkedAddOrCrash(size_t lhs, size_t rhs, llvm::StringRef fieldName) {
|
||||
size_t checkedMulOrCrash(size_t lhs, size_t rhs, llvm::StringRef fieldName) {
|
||||
if (lhs != 0 && rhs > std::numeric_limits<size_t>::max() / lhs) {
|
||||
emitCrashMessage(fieldName, "multiplication overflow");
|
||||
llvm_unreachable("Pim checked arithmetic failure");
|
||||
llvm_unreachable("PIM checked arithmetic failure");
|
||||
}
|
||||
return lhs * rhs;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#include "llvm/Support/raw_os_ostream.h"
|
||||
#include "llvm/Support/CommandLine.h"
|
||||
|
||||
#include <fstream>
|
||||
|
||||
@@ -7,12 +6,6 @@
|
||||
#include "src/Accelerators/PIM/Common/Support/FileSystemUtils.hpp"
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace {
|
||||
llvm::cl::opt<bool> dumpIr("pim-dump-ir", llvm::cl::init(false),
|
||||
llvm::cl::desc("Write PIM compiler IR snapshots (large constants are elided)"));
|
||||
}
|
||||
|
||||
bool isPimIrDumpEnabled() { return dumpIr; }
|
||||
|
||||
std::fstream openDialectDumpFileWithExtension(const std::string& name, llvm::StringRef destination, llvm::StringRef extension) {
|
||||
std::string outputDir = getOutputDir();
|
||||
@@ -25,7 +18,6 @@ std::fstream openDialectDumpFileWithExtension(const std::string& name, llvm::Str
|
||||
}
|
||||
|
||||
void dumpModule(mlir::ModuleOp moduleOp, const std::string& name, bool assumeVerified) {
|
||||
if (!dumpIr) return;
|
||||
std::fstream file = openDialectDumpFileWithExtension(name, "/dialects", "mlir");
|
||||
if (!file.is_open())
|
||||
return;
|
||||
|
||||
@@ -11,7 +11,6 @@ namespace onnx_mlir {
|
||||
/// Emits a MLIR snapshot under the current compiler output
|
||||
/// directory for pass-level debugging.
|
||||
void dumpModule(mlir::ModuleOp moduleOp, const std::string& name, bool assumeVerified = false);
|
||||
bool isPimIrDumpEnabled();
|
||||
|
||||
/// Opens a file under the same dialect dump directory used by dumpModule.
|
||||
std::fstream openDialectDumpFileWithExtension(const std::string& name,llvm::StringRef destination = "/dialects", llvm::StringRef extension = "mlir");
|
||||
|
||||
@@ -4,21 +4,6 @@
|
||||
|
||||
namespace onnx_mlir::pim {
|
||||
|
||||
static constexpr llvm::StringLiteral candidateResourceFailure = "pim.candidate-resource-limit";
|
||||
|
||||
mlir::InFlightDiagnostic emitCandidateResourceError(mlir::Operation *op, llvm::StringRef message) {
|
||||
auto diagnostic = op->emitError(message);
|
||||
diagnostic.getUnderlyingDiagnostic()->getMetadata().emplace_back(llvm::StringRef(candidateResourceFailure));
|
||||
return diagnostic;
|
||||
}
|
||||
|
||||
bool isCandidateResourceError(mlir::Diagnostic &diagnostic) {
|
||||
return llvm::any_of(diagnostic.getMetadata(), [](const mlir::DiagnosticArgument &argument) {
|
||||
return argument.getKind() == mlir::DiagnosticArgument::DiagnosticArgumentKind::String
|
||||
&& argument.getAsString() == candidateResourceFailure;
|
||||
});
|
||||
}
|
||||
|
||||
mlir::InFlightDiagnostic emitUnsupportedStaticShapeDiagnostic(mlir::Operation* op, llvm::StringRef valueDescription) {
|
||||
return op->emitOpError() << "requires statically shaped " << valueDescription;
|
||||
}
|
||||
|
||||
@@ -12,10 +12,6 @@
|
||||
|
||||
namespace onnx_mlir::pim {
|
||||
|
||||
/// Only a backend owner can classify a failed schedule as resource-infeasible.
|
||||
mlir::InFlightDiagnostic emitCandidateResourceError(mlir::Operation *op, llvm::StringRef message);
|
||||
bool isCandidateResourceError(mlir::Diagnostic &diagnostic);
|
||||
|
||||
struct CappedDiagnosticReporter {
|
||||
explicit CappedDiagnosticReporter(int64_t maxReportedFailures = 8)
|
||||
: maxReportedFailures(maxReportedFailures) {}
|
||||
|
||||
@@ -5,14 +5,7 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
namespace { thread_local bool suppressOutput = false; }
|
||||
ScopedCompilerOutputSuppression::ScopedCompilerOutputSuppression() : previous(suppressOutput) {
|
||||
suppressOutput = true;
|
||||
}
|
||||
ScopedCompilerOutputSuppression::~ScopedCompilerOutputSuppression() { suppressOutput = previous; }
|
||||
|
||||
std::string getOutputDir() {
|
||||
if (suppressOutput) return {};
|
||||
if (outputBaseName.empty() || outputBaseName == "-")
|
||||
return {};
|
||||
|
||||
|
||||
@@ -4,19 +4,10 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
/// Returns the directory that should hold Pim artifacts/debug dumps for the
|
||||
/// Returns the directory that should hold PIM artifacts/debug dumps for the
|
||||
/// current compiler invocation.
|
||||
std::string getOutputDir();
|
||||
|
||||
// Candidate lowering must not emit reports or temporary artifacts.
|
||||
class ScopedCompilerOutputSuppression {
|
||||
public:
|
||||
ScopedCompilerOutputSuppression();
|
||||
~ScopedCompilerOutputSuppression();
|
||||
private:
|
||||
bool previous;
|
||||
};
|
||||
|
||||
void createDirectory(const std::string& directory);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
|
||||
@@ -15,11 +15,6 @@ add_pim_library(OMPimCompilerOptions
|
||||
|
||||
add_pim_library(OMPimCompilerUtils
|
||||
PimCompilerUtils.cpp
|
||||
PimScheduleDiagnostic.cpp
|
||||
PimPeriodicAnalysis.cpp
|
||||
PimQueueReporting.cpp
|
||||
PimSpatialCost.cpp
|
||||
PimPipelineSelection.cpp
|
||||
PimArtifactWriter.cpp
|
||||
PimCodeGen.cpp
|
||||
PimCoreProgram.cpp
|
||||
@@ -47,8 +42,3 @@ add_pim_library(OMPimCompilerUtils
|
||||
ACCEL_INCLUDE_DIRS PRIVATE
|
||||
${PIM_ACCEL_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
add_onnx_mlir_executable(raptor-periodic NO_INSTALL
|
||||
PimPeriodicDiagnostic.cpp
|
||||
LINK_LIBS PRIVATE OMPimCompilerUtils
|
||||
)
|
||||
|
||||
@@ -140,13 +140,9 @@ OnnxMlirCompilerErrorCodes writeConfigJson(func::FuncOp funcOp,
|
||||
configJson["array_group_map"] = std::move(xbarsPerArrayGroup);
|
||||
|
||||
json::Array inputsAddresses;
|
||||
json::Array inputsSizes;
|
||||
for (BlockArgument input : funcOp.getArguments()) {
|
||||
for (BlockArgument input : funcOp.getArguments())
|
||||
inputsAddresses.push_back(memory.getValueAddress(input));
|
||||
inputsSizes.push_back(memory.hostMem.getMemEntry({input, std::nullopt}).size);
|
||||
}
|
||||
configJson["inputs_addresses"] = std::move(inputsAddresses);
|
||||
configJson["inputs_sizes"] = std::move(inputsSizes);
|
||||
|
||||
json::Array outputsAddresses;
|
||||
for (func::ReturnOp returnOp : funcOp.getOps<func::ReturnOp>())
|
||||
|
||||
@@ -14,7 +14,6 @@ namespace onnx_mlir::pim_binary {
|
||||
|
||||
inline constexpr char kMagic[4] = {'P', 'I', 'M', 'B'};
|
||||
inline constexpr uint32_t kVersion = 1;
|
||||
inline constexpr int32_t kMatrixWeightPrecisionBits = 8;
|
||||
inline constexpr uint64_t kCountOffset = 8;
|
||||
inline constexpr size_t kHeaderSize = 12;
|
||||
inline constexpr size_t kRecordSize = 20;
|
||||
@@ -163,8 +162,8 @@ inline constexpr std::array<InstructionJsonFormat, kOpcodeCount> kInstructionJso
|
||||
{true, true, true, "", "", "", "len" }, // lmv
|
||||
{true, false, true, "core", "", "", "size"}, // send
|
||||
{true, false, true, "core", "", "", "size"}, // recv
|
||||
{false, false, false, "", "event_register", "wait_value", ""}, // wait
|
||||
{false, false, false, "core", "event_register", "", ""}, // sync
|
||||
{false, false, false, "", "", "", "" }, // wait
|
||||
{false, false, false, "", "", "", "" }, // sync
|
||||
}};
|
||||
static_assert(kInstructionJsonFormats.size() == kOpcodeCount);
|
||||
|
||||
@@ -172,19 +171,19 @@ inline Opcode opcodeFromString(llvm::StringRef opName) {
|
||||
for (auto [index, name] : llvm::enumerate(kOpcodeNames))
|
||||
if (opName == name)
|
||||
return static_cast<Opcode>(index);
|
||||
llvm_unreachable("Unsupported Pim binary opcode");
|
||||
llvm_unreachable("Unsupported PIM binary opcode");
|
||||
}
|
||||
|
||||
inline llvm::StringRef opcodeToString(Opcode opcode) {
|
||||
size_t index = static_cast<size_t>(opcode);
|
||||
assert(index < kOpcodeNames.size() && "Unsupported Pim binary opcode");
|
||||
assert(index < kOpcodeNames.size() && "Unsupported PIM binary opcode");
|
||||
return kOpcodeNames[index];
|
||||
}
|
||||
|
||||
inline InstructionRecord makeInstructionRecord(const llvm::json::Object& instruction) {
|
||||
InstructionRecord record;
|
||||
std::optional<llvm::StringRef> opName = instruction.getString("op");
|
||||
assert(opName && "Missing op field in Pim instruction");
|
||||
assert(opName && "Missing op field in PIM instruction");
|
||||
record.opcode = opcodeFromString(*opName);
|
||||
const auto& format = kInstructionJsonFormats[static_cast<size_t>(record.opcode)];
|
||||
if (format.rd)
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
#include <utility>
|
||||
|
||||
#include "Common/IR/CompactAsmUtils.hpp"
|
||||
#include "Common/IR/ConstantUtils.hpp"
|
||||
#include "Common/PimCommon.hpp"
|
||||
#include "Common/Support/CheckedArithmetic.hpp"
|
||||
#include "Common/Support/Diagnostics.hpp"
|
||||
@@ -115,10 +114,18 @@ static bool isZeroSplatGlobal(mlir::Value value) {
|
||||
auto globalOp = moduleOp ? lookupGlobalForGetGlobal(moduleOp, getGlobalOp) : memref::GlobalOp();
|
||||
if (!globalOp || !globalOp.getConstant() || !globalOp.getInitialValue())
|
||||
return false;
|
||||
return isZeroBitPatternSplat(*globalOp.getInitialValue());
|
||||
auto denseAttr = dyn_cast<DenseElementsAttr>(*globalOp.getInitialValue());
|
||||
if (!denseAttr || !denseAttr.isSplat())
|
||||
return false;
|
||||
Attribute valueAttr = denseAttr.getSplatValue<Attribute>();
|
||||
if (auto floatAttr = dyn_cast<FloatAttr>(valueAttr))
|
||||
return floatAttr.getValue().isZero() && !floatAttr.getValue().isNegative();
|
||||
if (auto integerAttr = dyn_cast<IntegerAttr>(valueAttr))
|
||||
return integerAttr.getValue().isZero();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pim instruction immediates are serialized as signed int32_t fields today
|
||||
// PIM instruction immediates are serialized as signed int32_t fields today
|
||||
// (`sldi` goes through checkedI32OrCrash), so local addresses must stay within
|
||||
// the non-negative int32_t range.
|
||||
static FailureOr<size_t> checkedAlignTo(size_t value, size_t alignment, Operation* anchor, StringRef fieldName) {
|
||||
@@ -134,7 +141,7 @@ static void printMemoryOverflowDiagnostic(const MemoryValueKey& key,
|
||||
size_t requestedSize,
|
||||
size_t currentFirstAvailableAddress,
|
||||
size_t alignedEndAddress) {
|
||||
llvm::errs() << "Pim local memory allocation overflow\n";
|
||||
llvm::errs() << "PIM local memory allocation overflow\n";
|
||||
llvm::errs() << "Requested allocation size: " << requestedSize << " bytes\n";
|
||||
llvm::errs() << "Current firstAvailableAddress: " << currentFirstAvailableAddress << "\n";
|
||||
llvm::errs() << "Aligned end address: " << alignedEndAddress << "\n";
|
||||
@@ -180,7 +187,7 @@ size_t PimMemory::allocateAddress(size_t size, const MemoryValueKey& key) {
|
||||
size,
|
||||
firstAvailableAddress,
|
||||
succeeded(checkedAlignedEnd) ? *checkedAlignedEnd : kPimLocalMemoryAddressLimit);
|
||||
llvm_unreachable("Pim local memory allocation overflow");
|
||||
llvm_unreachable("PIM local memory allocation overflow");
|
||||
}
|
||||
firstAvailableAddress = *checkedAlignedEnd;
|
||||
return address;
|
||||
@@ -269,7 +276,7 @@ void PimMemory::allocateCore(const CompiledCoreMemoryPlan& plan, std::optional<u
|
||||
}
|
||||
else if (*localArenaSize != plan.arenaSize || reportRow.logicalLocalAllocationCount != plan.logicalAllocationCount
|
||||
|| reportRow.logicalLocalBytes != plan.logicalBytes)
|
||||
llvm_unreachable("inconsistent Pim local-memory plan across core-batch lanes");
|
||||
llvm_unreachable("inconsistent PIM local-memory plan across core-batch lanes");
|
||||
for (const CompiledLocalMemoryEntry& entry : plan.entries) {
|
||||
MemoryValueKey key = getMemoryValueKey(entry.value, lane);
|
||||
ownedMemEntriesMap[key] = entry.memory;
|
||||
@@ -345,8 +352,8 @@ size_t PimAcceleratorMemory::getValueAddress(mlir::Value value,
|
||||
llvm_unreachable("Missing mem entry");
|
||||
}
|
||||
|
||||
size_t byteOffset = pim::checkedSizeOrCrash(resolvedAddress->byteOffset, "resolved Pim byte offset");
|
||||
return pim::checkedAddOrCrash(iter->second.address, byteOffset, "resolved Pim address");
|
||||
size_t byteOffset = pim::checkedSizeOrCrash(resolvedAddress->byteOffset, "resolved PIM byte offset");
|
||||
return pim::checkedAddOrCrash(iter->second.address, byteOffset, "resolved PIM address");
|
||||
}
|
||||
|
||||
llvm::FailureOr<int64_t> PimAcceleratorMemory::getIndexValue(mlir::Value value,
|
||||
@@ -537,23 +544,11 @@ void PimCodeGen::setupRdRs1(size_t rdAddress, size_t rdOffset, size_t rs1Address
|
||||
genSetRegisterImmediateUnsigned(1, pim::checkedAddOrCrash(rs1Address, rs1Offset, "rs1 address"));
|
||||
}
|
||||
|
||||
std::array<uint8_t, 3> PimCodeGen::setupRdRs1Rs2(
|
||||
void PimCodeGen::setupRdRs1Rs2(
|
||||
size_t rdAddress, size_t rdOffset, size_t rs1Address, size_t rs1Offset, size_t rs2Address, size_t rs2Offset) const {
|
||||
size_t rd = pim::checkedAddOrCrash(rdAddress, rdOffset, "rd address");
|
||||
size_t rs1 = pim::checkedAddOrCrash(rs1Address, rs1Offset, "rs1 address");
|
||||
size_t rs2 = pim::checkedAddOrCrash(rs2Address, rs2Offset, "rs2 address");
|
||||
genSetRegisterImmediateUnsigned(0, rd);
|
||||
uint8_t rs1Register = 0;
|
||||
if (rd != rs1) {
|
||||
genSetRegisterImmediateUnsigned(1, rs1);
|
||||
rs1Register = 1;
|
||||
}
|
||||
if (rd == rs2)
|
||||
return {0, rs1Register, 0};
|
||||
if (rs1 == rs2)
|
||||
return {0, rs1Register, rs1Register};
|
||||
genSetRegisterImmediateUnsigned(2, rs2);
|
||||
return {0, rs1Register, 2};
|
||||
genSetRegisterImmediateUnsigned(0, pim::checkedAddOrCrash(rdAddress, rdOffset, "rd address"));
|
||||
genSetRegisterImmediateUnsigned(1, pim::checkedAddOrCrash(rs1Address, rs1Offset, "rs1 address"));
|
||||
genSetRegisterImmediateUnsigned(2, pim::checkedAddOrCrash(rs2Address, rs2Offset, "rs2 address"));
|
||||
}
|
||||
|
||||
void PimCodeGen::emitMemCopyOp(pim_binary::Opcode opcode,
|
||||
@@ -604,7 +599,7 @@ void PimCodeGen::emitMvmOp(size_t groupId, size_t rdAddr, size_t rdOffset, size_
|
||||
instruction.opcode = pim_binary::Opcode::mvmul;
|
||||
instruction.rd = 0;
|
||||
instruction.r1 = 1;
|
||||
instruction.r2OrImm = pim_binary::kMatrixWeightPrecisionBits;
|
||||
instruction.r2OrImm = 8;
|
||||
instruction.generic1 = 0;
|
||||
instruction.generic2 = pim::checkedI32OrCrash(groupId, "mvm group id");
|
||||
emitInstruction(instruction);
|
||||
@@ -669,13 +664,13 @@ void PimCodeGen::codeGenVMVOp(pim::PimVMVOp vmvOp, const StaticValueKnowledge& k
|
||||
auto sourceType = cast<ShapedType>(vmvOp.getSource().getType());
|
||||
int32_t bitwidth = getVectorElementBitwidthOrCrash(sourceType);
|
||||
ensureVectorBitwidth(bitwidth, bitwidth);
|
||||
auto registers = setupRdRs1Rs2(addressOf(vmvOp.getTarget(), knowledge), *targetOffset,
|
||||
addressOf(vmvOp.getSource(), knowledge), *sourceOffset, 0, *sourceStride);
|
||||
setupRdRs1Rs2(addressOf(vmvOp.getTarget(), knowledge), *targetOffset,
|
||||
addressOf(vmvOp.getSource(), knowledge), *sourceOffset, 0, *sourceStride);
|
||||
pim_binary::InstructionRecord instruction;
|
||||
instruction.opcode = pim_binary::Opcode::vmv;
|
||||
instruction.rd = registers[0];
|
||||
instruction.r1 = registers[1];
|
||||
instruction.r2OrImm = registers[2];
|
||||
instruction.rd = 0;
|
||||
instruction.r1 = 1;
|
||||
instruction.r2OrImm = 2;
|
||||
instruction.generic3 = vmvOp.getLength();
|
||||
emitInstruction(instruction);
|
||||
}
|
||||
@@ -697,41 +692,6 @@ void PimCodeGen::codeGenSendOp(pim::PimSendOp sendOp, const StaticValueKnowledge
|
||||
pim_binary::Opcode::send, addressOf(sendOp.getInput(), knowledge), *targetCoreId, sendOp.getSize());
|
||||
}
|
||||
|
||||
void PimCodeGen::codeGenWaitOp(
|
||||
pim::PimWaitOp waitOp, const StaticValueKnowledge& knowledge) const {
|
||||
if (pimDisableSynchronization)
|
||||
return;
|
||||
auto eventRegister = indexOf(waitOp.getEventRegister(), knowledge);
|
||||
auto waitValue = indexOf(waitOp.getWaitValue(), knowledge);
|
||||
assert(succeeded(eventRegister) && succeeded(waitValue)
|
||||
&& "pim.wait operands must be statically resolvable during codegen");
|
||||
if (*waitValue == 0)
|
||||
return;
|
||||
pim_binary::InstructionRecord instruction;
|
||||
instruction.opcode = pim_binary::Opcode::wait;
|
||||
instruction.generic1 = pim::checkedI32OrCrash(
|
||||
*eventRegister, "wait event register");
|
||||
instruction.generic2 = pim::checkedI32OrCrash(*waitValue, "wait value");
|
||||
emitInstruction(instruction);
|
||||
}
|
||||
|
||||
void PimCodeGen::codeGenSyncOp(
|
||||
pim::PimSyncOp syncOp, const StaticValueKnowledge& knowledge) const {
|
||||
if (pimDisableSynchronization)
|
||||
return;
|
||||
auto targetCoreId = indexOf(syncOp.getTargetCoreId(), knowledge);
|
||||
auto eventRegister = indexOf(syncOp.getEventRegister(), knowledge);
|
||||
assert(succeeded(targetCoreId) && succeeded(eventRegister)
|
||||
&& "pim.sync operands must be statically resolvable during codegen");
|
||||
pim_binary::InstructionRecord instruction;
|
||||
instruction.opcode = pim_binary::Opcode::sync;
|
||||
instruction.r2OrImm = pim::checkedI32OrCrash(
|
||||
*targetCoreId, "sync target core id");
|
||||
instruction.generic1 = pim::checkedI32OrCrash(
|
||||
*eventRegister, "sync event register");
|
||||
emitInstruction(instruction);
|
||||
}
|
||||
|
||||
void PimCodeGen::codeGenConcatOp(pim::PimConcatOp concatOp, const StaticValueKnowledge& knowledge) const {
|
||||
auto outputType = cast<ShapedType>(concatOp.getOutputBuffer().getType());
|
||||
assert(outputType.hasStaticShape() && "concat codegen requires static output shape");
|
||||
@@ -789,13 +749,12 @@ void PimCodeGen::emitBinaryVectorOp(pim_binary::Opcode opcode,
|
||||
auto inputType = cast<ShapedType>(lhs.getType());
|
||||
ensureVectorBitwidth(getVectorElementBitwidthOrCrash(inputType),
|
||||
getVectorElementBitwidthOrCrash(cast<ShapedType>(output.getType())));
|
||||
auto registers = setupRdRs1Rs2(
|
||||
addressOf(output, knowledge), 0, addressOf(lhs, knowledge), 0, addressOf(rhs, knowledge), 0);
|
||||
setupRdRs1Rs2(addressOf(output, knowledge), 0, addressOf(lhs, knowledge), 0, addressOf(rhs, knowledge), 0);
|
||||
pim_binary::InstructionRecord instruction;
|
||||
instruction.opcode = opcode;
|
||||
instruction.rd = registers[0];
|
||||
instruction.r1 = registers[1];
|
||||
instruction.r2OrImm = registers[2];
|
||||
instruction.rd = 0;
|
||||
instruction.r1 = 1;
|
||||
instruction.r2OrImm = 2;
|
||||
instruction.generic3 = getVectorElementCountOrCrash(inputType);
|
||||
emitInstruction(instruction);
|
||||
}
|
||||
@@ -955,7 +914,7 @@ static LogicalResult executeCompiledCorePlan(
|
||||
auto step = node.step.evaluate(knowledge);
|
||||
auto forOp = cast<mlir::scf::ForOp>(node.op);
|
||||
if (failed(lowerBound) || failed(upperBound) || failed(step) || *step <= 0) {
|
||||
forOp.emitOpError("requires statically evaluable scf.for bounds for Pim codegen");
|
||||
forOp.emitOpError("requires statically evaluable scf.for bounds for PIM codegen");
|
||||
return failure();
|
||||
}
|
||||
|
||||
@@ -981,7 +940,7 @@ static LogicalResult executeCompiledCorePlan(
|
||||
auto condition = node.condition.evaluate(knowledge);
|
||||
auto ifOp = cast<mlir::scf::IfOp>(node.op);
|
||||
if (failed(condition)) {
|
||||
ifOp.emitOpError("requires statically evaluable scf.if condition for Pim codegen");
|
||||
ifOp.emitOpError("requires statically evaluable scf.if condition for PIM codegen");
|
||||
return failure();
|
||||
}
|
||||
|
||||
@@ -995,7 +954,7 @@ static LogicalResult executeCompiledCorePlan(
|
||||
auto selector = node.condition.evaluate(knowledge);
|
||||
auto switchOp = cast<mlir::scf::IndexSwitchOp>(node.op);
|
||||
if (failed(selector)) {
|
||||
switchOp.emitOpError("requires a statically evaluable scf.index_switch selector for Pim codegen");
|
||||
switchOp.emitOpError("requires a statically evaluable scf.index_switch selector for PIM codegen");
|
||||
return failure();
|
||||
}
|
||||
const llvm::SmallVectorImpl<CompiledCoreNode>* selectedBody = node.defaultBody.get();
|
||||
@@ -1032,8 +991,6 @@ static LogicalResult executeCompiledCorePlan(
|
||||
case CompiledCoreOpKind::VMV: coreCodeGen.codeGenVMVOp(cast<pim::PimVMVOp>(node.op), knowledge); break;
|
||||
case CompiledCoreOpKind::Receive: coreCodeGen.codeGenReceiveOp(cast<pim::PimReceiveOp>(node.op), knowledge); break;
|
||||
case CompiledCoreOpKind::Send: coreCodeGen.codeGenSendOp(cast<pim::PimSendOp>(node.op), knowledge); break;
|
||||
case CompiledCoreOpKind::Wait: coreCodeGen.codeGenWaitOp(cast<pim::PimWaitOp>(node.op), knowledge); break;
|
||||
case CompiledCoreOpKind::Sync: coreCodeGen.codeGenSyncOp(cast<pim::PimSyncOp>(node.op), knowledge); break;
|
||||
case CompiledCoreOpKind::Concat: coreCodeGen.codeGenConcatOp(cast<pim::PimConcatOp>(node.op), knowledge); break;
|
||||
case CompiledCoreOpKind::Vmm:
|
||||
if (auto weightSlot = resolveWeightSlot(cast<pim::PimVMMOp>(node.op), knowledge); succeeded(weightSlot))
|
||||
@@ -1181,12 +1138,12 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
}
|
||||
auto getCompiledProgram = [&](Operation* op) {
|
||||
auto it = compiledPrograms.find(op);
|
||||
assert(it != compiledPrograms.end() && "missing compiled Pim core program");
|
||||
assert(it != compiledPrograms.end() && "missing compiled PIM core program");
|
||||
return it->second.get();
|
||||
};
|
||||
auto getMemoryPlan = [&](Operation* op) {
|
||||
auto it = memoryPlans.find(op);
|
||||
assert(it != memoryPlans.end() && "missing Pim core memory plan");
|
||||
assert(it != memoryPlans.end() && "missing PIM core memory plan");
|
||||
return it->second.get();
|
||||
};
|
||||
|
||||
@@ -1264,7 +1221,7 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
if (failed(weightView)) {
|
||||
std::string message;
|
||||
llvm::raw_string_ostream os(message);
|
||||
os << "requires a statically resolvable dense global weight view during Pim codegen; weight="
|
||||
os << "requires a statically resolvable dense global weight view during PIM codegen; weight="
|
||||
<< vmmOp.getWeight() << " type=" << vmmOp.getWeight().getType();
|
||||
result.recordDiagnostic(vmmOp, os.str());
|
||||
return failure();
|
||||
@@ -1272,7 +1229,7 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
if (weightView->shape.size() != 2) {
|
||||
std::string message;
|
||||
llvm::raw_string_ostream os(message);
|
||||
os << "requires a rank-2 matrix weight view during Pim codegen; resolved shape=[";
|
||||
os << "requires a rank-2 matrix weight view during PIM codegen; resolved shape=[";
|
||||
llvm::interleaveComma(weightView->shape, os);
|
||||
os << "] weight=" << vmmOp.getWeight() << " type=" << vmmOp.getWeight().getType();
|
||||
result.recordDiagnostic(vmmOp, os.str());
|
||||
@@ -1288,13 +1245,12 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
|
||||
std::error_code errorCode;
|
||||
auto outputCorePath = outputDirPath + "/core_" + std::to_string(job.physicalCoreId) + ".pim";
|
||||
auto fileStream = std::make_unique<raw_fd_ostream>(outputCorePath, errorCode, sys::fs::OF_None);
|
||||
raw_fd_ostream coreBinaryStream(outputCorePath, errorCode, sys::fs::OF_None);
|
||||
if (errorCode) {
|
||||
errs() << "Error opening core file: " << outputCorePath << ": " << errorCode.message() << '\n';
|
||||
errs() << "Error while opening core file `" << outputCorePath << "`: " << errorCode.message() << '\n';
|
||||
result.status = InvalidOutputFileAccess;
|
||||
return result;
|
||||
}
|
||||
raw_pwrite_stream &coreBinaryStream = *fileStream;
|
||||
|
||||
std::unique_ptr<raw_fd_ostream> coreJsonStream;
|
||||
if (pimEmitJson.getValue()) {
|
||||
@@ -1313,8 +1269,11 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
PimCodeGen coreCodeGen(jobMemory, instructionWriter, coreJsonStream.get());
|
||||
auto finalizeInstructions = [&]() {
|
||||
bool succeeded = mlir::succeeded(instructionWriter.finalize());
|
||||
fileStream->close();
|
||||
if (fileStream->has_error()) { fileStream->clear_error(); succeeded = false; }
|
||||
coreBinaryStream.close();
|
||||
if (coreBinaryStream.has_error()) {
|
||||
coreBinaryStream.clear_error();
|
||||
succeeded = false;
|
||||
}
|
||||
return succeeded;
|
||||
};
|
||||
|
||||
@@ -1382,7 +1341,7 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
}
|
||||
if (diagnostics.hasFailure())
|
||||
diagnostics.emitSuppressedSummary(summaryAnchor ? summaryAnchor : moduleOp.getOperation(),
|
||||
"Pim codegen diagnostic(s)");
|
||||
"PIM codegen diagnostic(s)");
|
||||
|
||||
for (size_t jobIndex = 0; jobIndex < jobs.size(); ++jobIndex)
|
||||
if (jobResults[jobIndex].status != CompilerSuccess)
|
||||
@@ -1398,7 +1357,8 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
physicalCoreId < activePhysicalCores.size(); ++physicalCoreId) {
|
||||
if (activePhysicalCores[physicalCoreId])
|
||||
continue;
|
||||
if (auto err = emitEmptyCoreArtifacts(outputDirPath, physicalCoreId))
|
||||
if (auto err =
|
||||
emitEmptyCoreArtifacts(outputDirPath, physicalCoreId))
|
||||
return err;
|
||||
xbarsPerArrayGroup["core" + std::to_string(physicalCoreId)] =
|
||||
json::Array {};
|
||||
@@ -1447,7 +1407,7 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
if (!batchPerCoreRow)
|
||||
batchPerCoreRow = result.reportRow;
|
||||
else if (!(*batchPerCoreRow == result.reportRow))
|
||||
llvm_unreachable("one Pim core batch produced inconsistent per-core memory reports");
|
||||
llvm_unreachable("one PIM core batch produced inconsistent per-core memory reports");
|
||||
}
|
||||
|
||||
uint64_t batchReportId = jobs[group.front()].batchReportId.value_or(0);
|
||||
|
||||
@@ -176,7 +176,7 @@ class PimCodeGen {
|
||||
void genSetRegisterImmediateUnsigned(size_t registerNumber, size_t immediate) const;
|
||||
void setupRd(size_t rdAddress, size_t rdOffset) const;
|
||||
void setupRdRs1(size_t rdAddress, size_t rdOffset, size_t rs1Address, size_t rs1Offset) const;
|
||||
std::array<uint8_t, 3> setupRdRs1Rs2(
|
||||
void setupRdRs1Rs2(
|
||||
size_t rdAddress, size_t rdOffset, size_t rs1Address, size_t rs1Offset, size_t rs2Address, size_t rs2Offset) const;
|
||||
|
||||
void emitMemCopyOp(pim_binary::Opcode opcode,
|
||||
@@ -217,8 +217,6 @@ public:
|
||||
|
||||
void codeGenReceiveOp(pim::PimReceiveOp receiveOp, const StaticValueKnowledge& knowledge) const;
|
||||
void codeGenSendOp(pim::PimSendOp sendOp, const StaticValueKnowledge& knowledge) const;
|
||||
void codeGenWaitOp(pim::PimWaitOp waitOp, const StaticValueKnowledge& knowledge) const;
|
||||
void codeGenSyncOp(pim::PimSyncOp syncOp, const StaticValueKnowledge& knowledge) const;
|
||||
void codeGenConcatOp(pim::PimConcatOp concatOp, const StaticValueKnowledge& knowledge) const;
|
||||
|
||||
template <typename MVMTy>
|
||||
|
||||
@@ -2,32 +2,30 @@
|
||||
|
||||
#include "src/Accelerators/PIM/Compiler/PimCompilerOptions.hpp"
|
||||
|
||||
#include <limits>
|
||||
|
||||
#define DEBUG_TYPE "PimCompilerOptions"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
llvm::cl::opt<PimEmissionTargetType> pimEmissionTarget(
|
||||
llvm::cl::desc("[Optional] Choose Pim-related target to emit (once selected it will cancel the other targets):"),
|
||||
llvm::cl::values(clEnumVal(EmitSpatial, "Lower model to Spatial IR")),
|
||||
llvm::cl::values(clEnumVal(EmitPim, "Lower model to Pim IR")),
|
||||
llvm::cl::values(clEnumVal(EmitPimBufferized, "Lower model to Pim IR and bufferize it")),
|
||||
llvm::cl::values(clEnumVal(EmitPimCodegen, "Lower model to Pim IR and generate code for Pim")),
|
||||
llvm::cl::desc("[Optional] Choose PIM-related target to emit (once selected it will cancel the other targets):"),
|
||||
llvm::cl::values(clEnumVal(EmitSpatial, "Lower model to spatial IR")),
|
||||
llvm::cl::values(clEnumVal(EmitPim, "Lower model to PIM IR")),
|
||||
llvm::cl::values(clEnumVal(EmitPimBufferized, "Lower model to PIM IR and bufferize it")),
|
||||
llvm::cl::values(clEnumVal(EmitPimCodegen, "Lower model to PIM IR and generate code for PIM")),
|
||||
llvm::cl::init(EmitPimCodegen),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<PimMemoryReportLevel> pimMemoryReport(
|
||||
"pim-memory-report",
|
||||
llvm::cl::desc("Emit a human-readable Pim memory planning report"),
|
||||
llvm::cl::values(clEnumValN(PimMemoryReportNone, "none", "Do not emit any Pim memory planning report")),
|
||||
llvm::cl::values(clEnumValN(PimMemoryReportSummary, "summary", "Emit a concise Pim memory summary")),
|
||||
llvm::cl::desc("Emit a human-readable PIM memory planning report"),
|
||||
llvm::cl::values(clEnumValN(PimMemoryReportNone, "none", "Do not emit any PIM memory planning report")),
|
||||
llvm::cl::values(clEnumValN(PimMemoryReportSummary, "summary", "Emit a concise PIM memory summary")),
|
||||
llvm::cl::init(PimMemoryReportSummary),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<PimConvLoweringType> pimConvLowering(
|
||||
"pim-conv-lowering",
|
||||
llvm::cl::desc("Convolution lowering strategy for Pim"),
|
||||
llvm::cl::desc("Convolution lowering strategy for PIM"),
|
||||
llvm::cl::values(clEnumValN(PimConvLoweringAuto, "auto", "Select the Conv lowering strategy automatically")),
|
||||
llvm::cl::values(clEnumValN(PimConvLoweringLegacy, "legacy", "Use the legacy explicit-im2col Conv lowering")),
|
||||
llvm::cl::values(clEnumValN(PimConvLoweringDepthwise, "depthwise", "Force the depthwise-specialized Conv lowering")),
|
||||
@@ -55,23 +53,28 @@ llvm::cl::opt<PimSpatialDataflowExportType> pimExportSpatialDataflow(
|
||||
llvm::cl::desc("Emit Gephi-importable CSV dataflow reports for Spatial pipeline snapshots"),
|
||||
llvm::cl::values(clEnumValN(SpatialDataflowExportNone, "none", "Do not emit Spatial dataflow CSV reports")),
|
||||
llvm::cl::values(
|
||||
clEnumValN(SpatialDataflowExportSpatial1, "spatial1", "Emit Spatial1 graph dataflow CSV reports")),
|
||||
clEnumValN(SpatialDataflowExportSpatial1, "spatial1", "Emit spatial1 graph dataflow CSV reports")),
|
||||
llvm::cl::values(
|
||||
clEnumValN(SpatialDataflowExportSpatial2, "spatial2", "Emit Spatial2 trivially merged graph dataflow CSV reports")),
|
||||
clEnumValN(SpatialDataflowExportSpatial2, "spatial2", "Emit spatial2 trivially merged graph dataflow CSV reports")),
|
||||
llvm::cl::values(
|
||||
clEnumValN(SpatialDataflowExportSpatial3, "spatial3", "Emit Spatial3 scheduled dataflow CSV reports")),
|
||||
clEnumValN(SpatialDataflowExportSpatial3, "spatial3", "Emit spatial3 scheduled dataflow CSV reports")),
|
||||
llvm::cl::values(
|
||||
clEnumValN(SpatialDataflowExportSpatial4, "spatial4", "Emit Spatial4 realized dataflow CSV reports")),
|
||||
clEnumValN(SpatialDataflowExportSpatial4, "spatial4", "Emit spatial4 realized dataflow CSV reports")),
|
||||
llvm::cl::values(clEnumValN(SpatialDataflowExportAll, "all", "Emit all Spatial dataflow CSV reports")),
|
||||
llvm::cl::init(SpatialDataflowExportNone),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool>
|
||||
pimOnlyCodegen("pim-only-codegen",
|
||||
llvm::cl::desc("Only generate code for Pim (assume input is already in bufferized Pim IR)"),
|
||||
llvm::cl::desc("Only generate code for PIM (assume input is already in bufferized PIM IR)"),
|
||||
llvm::cl::init(false),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> useExperimentalConvImpl("use-experimental-conv-impl",
|
||||
llvm::cl::desc("Use experimental implementation for convolution"),
|
||||
llvm::cl::init(false),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<uint64_t> pimConvIm2colMaxElements(
|
||||
"pim-conv-im2col-max-elements",
|
||||
llvm::cl::desc("Maximum number of im2col elements to materialize globally for one Conv before streaming/chunking"),
|
||||
@@ -84,15 +87,6 @@ llvm::cl::opt<uint64_t> pimConvStreamChunkPositions(
|
||||
llvm::cl::init(1024),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimReportConvLowering("pim-report-conv-lowering",
|
||||
llvm::cl::desc("Emit a bounded Conv lowering report"),
|
||||
llvm::cl::init(true),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimPeriodicDiagnostics("pim-periodic-diagnostics",
|
||||
llvm::cl::desc("Emit optional Spatial recurrence and execution-work reports"),
|
||||
llvm::cl::init(false), llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimEmitJson("pim-emit-json",
|
||||
llvm::cl::desc("Also emit per-core JSON instruction files alongside binary .pim files"),
|
||||
llvm::cl::init(false),
|
||||
@@ -100,83 +94,50 @@ llvm::cl::opt<bool> pimEmitJson("pim-emit-json",
|
||||
|
||||
llvm::cl::opt<bool> pimDetectCommunicationDeadlock(
|
||||
"pim-detect-communication-deadlock",
|
||||
llvm::cl::desc("Expensively simulate statically expanded Pim SEND/RECV and exact-count SYNC/WAIT order at verification time and fail on a blocking deadlock"),
|
||||
llvm::cl::desc("Expensively simulate the statically expanded PIM send/receive order at verification time and fail if a blocking communication deadlock is found"),
|
||||
llvm::cl::init(false),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimVerifyBufferizationCopyFreedom(
|
||||
"pim-verify-bufferization-copy-freedom",
|
||||
llvm::cl::desc("Run the expensive official Pim tensor-copy freedom proof before bufferization"),
|
||||
llvm::cl::opt<bool> pimMaterializeScalarFanoutGlobalOrder(
|
||||
"pim-materialize-scalar-fanout-global-order",
|
||||
llvm::cl::desc("Experimental expensive materializer mode: emit scalar-source fanout as globally ordered communication events instead of all-send fanout loops"),
|
||||
llvm::cl::init(false),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimDisableSynchronization(
|
||||
"pim-disable-synchronization",
|
||||
llvm::cl::desc("Omit Pim wait/sync instructions from generated code for performance ablation"),
|
||||
llvm::cl::init(false),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimDisableSpatialPlanning(
|
||||
"pim-disable-spatial-planning",
|
||||
llvm::cl::desc("Select the trivial Spatial layout plan for performance ablation"),
|
||||
llvm::cl::opt<bool> pimTraceCommunicationMaterialization(
|
||||
"pim-trace-communication-materialization",
|
||||
llvm::cl::desc("Emit verbose materializer-time diagnostics and provenance attributes for every Spatial communication op"),
|
||||
llvm::cl::init(false),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<size_t>
|
||||
crossbarSize("crossbar-size",
|
||||
llvm::cl::desc("Width and height of a single crossbar (required for Pim compilation)"),
|
||||
llvm::cl::init(0));
|
||||
crossbarSize("crossbar-size", llvm::cl::desc("Width and height of a single crossbar"), llvm::cl::init(128));
|
||||
|
||||
llvm::cl::opt<size_t>
|
||||
crossbarCountInCore("crossbar-count",
|
||||
llvm::cl::desc("Number of crossbars in each core (required for Pim compilation)"),
|
||||
llvm::cl::init(0));
|
||||
|
||||
llvm::cl::opt<std::string> pipelineStages(
|
||||
"pipeline",
|
||||
llvm::cl::desc("Exactly N nonempty stages, or auto for throughput depth selection (default: 1, latency PEFT)"),
|
||||
llvm::cl::init("1"),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
size_t getPimPipelineStages() {
|
||||
llvm::StringRef value(pipelineStages.getValue());
|
||||
if (value == "auto") return 0;
|
||||
size_t stages;
|
||||
if (value.getAsInteger(10, stages) || !stages)
|
||||
llvm::report_fatal_error("Pim compilation requires --pipeline=<positive integer|auto>");
|
||||
return stages;
|
||||
}
|
||||
crossbarCountInCore("crossbar-count", llvm::cl::desc("Number of crossbars in each core"), llvm::cl::init(64));
|
||||
|
||||
llvm::cl::opt<long> coresCount("core-count",
|
||||
llvm::cl::desc("Number of cores in the chip. Required for Pim compilation."),
|
||||
llvm::cl::desc("Number of cores in the chip. Required for PIM compilation."),
|
||||
llvm::cl::init(-1));
|
||||
|
||||
llvm::cl::opt<std::string> pimTargetConfig(
|
||||
"pim-target-config",
|
||||
llvm::cl::desc("Pim target configuration used to construct the Spatial scheduling cost model"),
|
||||
llvm::cl::desc("PIM target configuration used to construct the Spatial scheduling cost model"),
|
||||
llvm::cl::init(""),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
void verifyPimCompilerOptions() {
|
||||
if (coresCount.getNumOccurrences() == 0)
|
||||
llvm::report_fatal_error("Pim compilation requires an explicit --core-count=<positive integer>");
|
||||
llvm::cl::opt<bool>
|
||||
ignoreConcatError("ignore-concat-error",
|
||||
llvm::cl::desc("Ignore ConcatOp corner case: do not assert and do a simplification"),
|
||||
llvm::cl::init(false));
|
||||
|
||||
bool hasExplicitPimCoreCount() { return coresCount.getNumOccurrences() != 0; }
|
||||
|
||||
void verifyExplicitPimCoreCount() {
|
||||
if (!hasExplicitPimCoreCount())
|
||||
llvm::report_fatal_error("PIM compilation requires an explicit --core-count=<positive integer>");
|
||||
if (coresCount.getValue() <= 0)
|
||||
llvm::report_fatal_error("Pim compilation requires --core-count to be a positive integer");
|
||||
if (crossbarSize.getNumOccurrences() == 0)
|
||||
llvm::report_fatal_error("Pim compilation requires an explicit --crossbar-size=<positive integer>");
|
||||
if (crossbarSize.getValue() == 0)
|
||||
llvm::report_fatal_error("Pim compilation requires --crossbar-size to be a positive integer");
|
||||
if (crossbarCountInCore.getNumOccurrences() == 0)
|
||||
llvm::report_fatal_error("Pim compilation requires an explicit --crossbar-count=<positive integer>");
|
||||
if (crossbarCountInCore.getValue() == 0)
|
||||
llvm::report_fatal_error("Pim compilation requires --crossbar-count to be a positive integer");
|
||||
size_t stages = getPimPipelineStages();
|
||||
if (static_cast<size_t>(coresCount.getValue()) < stages)
|
||||
llvm::report_fatal_error("Pim compilation requires --pipeline not to exceed --core-count");
|
||||
size_t maximumStages = stages ? stages : static_cast<size_t>(coresCount.getValue());
|
||||
if (crossbarCountInCore.getValue()
|
||||
> std::numeric_limits<size_t>::max() / maximumStages)
|
||||
llvm::report_fatal_error("Pim compilation --crossbar-count * --pipeline overflows");
|
||||
llvm::report_fatal_error("PIM compilation requires --core-count to be a positive integer");
|
||||
}
|
||||
|
||||
} // namespace onnx_mlir
|
||||
|
||||
@@ -55,24 +55,28 @@ extern llvm::cl::opt<PimConvLoweringType> pimConvLowering;
|
||||
extern llvm::cl::opt<PimSpatialDataflowExportType> pimExportSpatialDataflow;
|
||||
|
||||
extern llvm::cl::opt<bool> pimOnlyCodegen;
|
||||
extern llvm::cl::opt<bool> useExperimentalConvImpl;
|
||||
extern llvm::cl::opt<bool> pimEmitJson;
|
||||
extern llvm::cl::opt<bool> pimPeriodicDiagnostics;
|
||||
extern llvm::cl::opt<bool> pimReportConvLowering;
|
||||
extern llvm::cl::opt<bool> pimDetectCommunicationDeadlock;
|
||||
extern llvm::cl::opt<bool> pimVerifyBufferizationCopyFreedom;
|
||||
extern llvm::cl::opt<bool> pimDisableSynchronization;
|
||||
extern llvm::cl::opt<bool> pimDisableSpatialPlanning;
|
||||
extern llvm::cl::opt<bool> pimMaterializeScalarFanoutGlobalOrder;
|
||||
extern llvm::cl::opt<bool> pimTraceCommunicationMaterialization;
|
||||
|
||||
extern llvm::cl::opt<size_t> crossbarSize;
|
||||
extern llvm::cl::opt<size_t> crossbarCountInCore;
|
||||
extern llvm::cl::opt<std::string> pipelineStages;
|
||||
// Zero denotes automatic depth internally; numeric zero is never accepted.
|
||||
size_t getPimPipelineStages();
|
||||
extern llvm::cl::opt<long> coresCount;
|
||||
extern llvm::cl::opt<std::string> pimTargetConfig;
|
||||
extern llvm::cl::opt<uint64_t> pimConvIm2colMaxElements;
|
||||
extern llvm::cl::opt<uint64_t> pimConvStreamChunkPositions;
|
||||
|
||||
void verifyPimCompilerOptions();
|
||||
bool hasExplicitPimCoreCount();
|
||||
void verifyExplicitPimCoreCount();
|
||||
|
||||
// This option, by default set to false, will ignore an error when resolving a
|
||||
// specific tiles of the operands of a concat. This specific case is when the
|
||||
// wanted tile is generated by two separate operands of the concat. If this is
|
||||
// set to false, this corner case will assert an error. If this is set to true,
|
||||
// a simplification is performed and only the tile from the first operand is
|
||||
// taken.
|
||||
extern llvm::cl::opt<bool> ignoreConcatError;
|
||||
|
||||
} // namespace onnx_mlir
|
||||
|
||||
@@ -12,18 +12,13 @@
|
||||
#include <limits>
|
||||
#include <tuple>
|
||||
|
||||
#include "src/Accelerators/PIM/Common/PimCommon.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCompilerOptions.hpp"
|
||||
#include "PimPipelineSelection.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "PimSpatialCost.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCompilerUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Conversion/ONNXToSpatial/ONNXToSpatialOptions.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Pim/PimOps.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/SpatialTargetResources.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/SpatialDataflowCsvExporter.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
#include "src/Accelerators/PIM/Passes/PIMPasses.h"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/SpatialTargetInfo.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Transforms/MergeComputeNodes/ScheduledSpatialPasses.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
#include "src/Accelerators/PIM/Pass/PIMPasses.h"
|
||||
#include "src/Compiler/CompilerPasses.hpp"
|
||||
|
||||
#define DEBUG_TYPE "PimCompilerUtils"
|
||||
@@ -81,14 +76,7 @@ spatial::SchedulingTarget getDefaultPimSchedulingTarget() {
|
||||
target.processorCount = static_cast<size_t>(coresCount.getValue());
|
||||
target.residentWeightCapacity = crossbarCountInCore.getValue();
|
||||
target.matrixRows = crossbarSize.getValue();
|
||||
// The oracle charges eight input reads for each matrix operation.
|
||||
target.matrixInputReadMultiplier = 8;
|
||||
target.matrixColumns = crossbarSize.getValue();
|
||||
target.synchronizationRegisterCount = kPimEventRegisterCount;
|
||||
target.sharedMemoryWidthBytes = 16;
|
||||
target.sharedMemoryReadLatencyNs = 8;
|
||||
target.sharedMemoryWriteLatencyNs = 10;
|
||||
target.zeroSplatUsesSharedMemory = false;
|
||||
|
||||
setDefaultPimInterProcessorLatencies(target);
|
||||
return target;
|
||||
@@ -106,40 +94,20 @@ spatial::ConvLoweringStrategy getSpatialConvLoweringStrategy(PimConvLoweringType
|
||||
case PimConvLoweringInputKTiled: return spatial::ConvLoweringStrategy::InputKTiled;
|
||||
case PimConvLoweringTiled2D: return spatial::ConvLoweringStrategy::Tiled2D;
|
||||
}
|
||||
llvm_unreachable("unknown Pim Conv lowering strategy");
|
||||
llvm_unreachable("unknown PIM Conv lowering strategy");
|
||||
}
|
||||
|
||||
spatial::SpatialDataflowExportStage getPimSpatialDataflowExportStage(
|
||||
PimSpatialDataflowExportType stage) {
|
||||
switch (stage) {
|
||||
case SpatialDataflowExportNone: return spatial::SpatialDataflowExportStage::None;
|
||||
case SpatialDataflowExportSpatial1: return spatial::SpatialDataflowExportStage::Spatial1;
|
||||
case SpatialDataflowExportSpatial2: return spatial::SpatialDataflowExportStage::Spatial2;
|
||||
case SpatialDataflowExportSpatial3: return spatial::SpatialDataflowExportStage::Spatial3;
|
||||
case SpatialDataflowExportSpatial4: return spatial::SpatialDataflowExportStage::Spatial4;
|
||||
case SpatialDataflowExportAll: return spatial::SpatialDataflowExportStage::All;
|
||||
}
|
||||
llvm_unreachable("unknown Pim Spatial dataflow export stage");
|
||||
}
|
||||
|
||||
spatial::SpatialTargetResources getPimSpatialTargetResources(const spatial::SchedulingTarget& target) {
|
||||
spatial::SpatialTargetResources resources;
|
||||
resources.matrixShape = {target.matrixRows, target.matrixColumns};
|
||||
resources.matrixUnitsPerProcessor = target.residentWeightCapacity;
|
||||
resources.processorCount = target.processorCount;
|
||||
resources.vectorWidth = target.vectorWidth;
|
||||
if (failed(resources.verify()))
|
||||
llvm::report_fatal_error("Pim target resources are incomplete");
|
||||
return resources;
|
||||
}
|
||||
|
||||
ONNXToSpatialPlanningOptions getPimONNXToSpatialPlanningOptions() {
|
||||
ONNXToSpatialPlanningOptions options;
|
||||
options.convIm2colMaxElements = pimConvIm2colMaxElements.getValue();
|
||||
options.convStreamChunkPositions = pimConvStreamChunkPositions.getValue();
|
||||
options.forcedConvStrategy = getSpatialConvLoweringStrategy(pimConvLowering.getValue());
|
||||
options.reportConvLowering = pimReportConvLowering.getValue();
|
||||
return options;
|
||||
spatial::SpatialTargetInfo getPimSpatialTargetInfo(const spatial::SchedulingTarget& target) {
|
||||
spatial::SpatialTargetInfo info;
|
||||
info.matrixShape = {target.matrixRows, target.matrixColumns};
|
||||
info.matrixUnitsPerProcessor = target.residentWeightCapacity;
|
||||
info.processorCount = target.processorCount;
|
||||
info.vectorWidth = target.vectorWidth;
|
||||
info.convIm2colMaxElements = pimConvIm2colMaxElements.getValue();
|
||||
info.convStreamChunkPositions = pimConvStreamChunkPositions.getValue();
|
||||
info.convLoweringStrategy = getSpatialConvLoweringStrategy(pimConvLowering.getValue());
|
||||
info.useExperimentalConvImplementation = useExperimentalConvImpl.getValue();
|
||||
return info;
|
||||
}
|
||||
|
||||
const llvm::json::Object& requireObject(const llvm::json::Object& object,
|
||||
@@ -147,7 +115,7 @@ const llvm::json::Object& requireObject(const llvm::json::Object& object,
|
||||
llvm::StringRef path) {
|
||||
const llvm::json::Object* nested = object.getObject(key);
|
||||
if (!nested)
|
||||
llvm::report_fatal_error("Pim target config is missing object '" + path + "." + key + "'");
|
||||
llvm::report_fatal_error("PIM target config is missing object '" + path + "." + key + "'");
|
||||
return *nested;
|
||||
}
|
||||
|
||||
@@ -160,7 +128,7 @@ Cost getConfigCost(const llvm::json::Object& object,
|
||||
return fallback;
|
||||
if (!std::isfinite(*number) || *number < 0.0 || (!allowZero && *number == 0.0)
|
||||
|| *number > static_cast<double>(std::numeric_limits<Cost>::max()))
|
||||
llvm::report_fatal_error("Pim target config field '" + key + "' must be a valid positive number");
|
||||
llvm::report_fatal_error("PIM target config field '" + key + "' must be a valid positive number");
|
||||
return static_cast<Cost>(std::ceil(*number));
|
||||
}
|
||||
|
||||
@@ -168,23 +136,22 @@ std::pair<size_t, size_t> getConfigPair(const llvm::json::Object& object,
|
||||
llvm::StringRef key) {
|
||||
const llvm::json::Array* values = object.getArray(key);
|
||||
if (!values || values->size() != 2)
|
||||
llvm::report_fatal_error("Pim target config field '" + key + "' must contain two integers");
|
||||
llvm::report_fatal_error("PIM target config field '" + key + "' must contain two integers");
|
||||
std::optional<int64_t> first = (*values)[0].getAsInteger();
|
||||
std::optional<int64_t> second = (*values)[1].getAsInteger();
|
||||
if (!first || !second || *first <= 0 || *second <= 0)
|
||||
llvm::report_fatal_error("Pim target config field '" + key + "' must contain two positive integers");
|
||||
llvm::report_fatal_error("PIM target config field '" + key + "' must contain two positive integers");
|
||||
return {static_cast<size_t>(*first), static_cast<size_t>(*second)};
|
||||
}
|
||||
|
||||
void loadPimInterProcessorLatencies(
|
||||
PimInstructionTiming& target,
|
||||
const llvm::json::Object& network,
|
||||
std::optional<int64_t> memorySwitch) {
|
||||
spatial::SchedulingTarget& target,
|
||||
const llvm::json::Object& network) {
|
||||
std::optional<llvm::StringRef> filename =
|
||||
network.getString("net_config_file_path");
|
||||
if (!filename)
|
||||
llvm::report_fatal_error(
|
||||
"Pim target config is missing network latency file path");
|
||||
"PIM target config is missing network latency file path");
|
||||
|
||||
llvm::SmallString<256> networkPath(*filename);
|
||||
if (!llvm::sys::path::is_absolute(networkPath)) {
|
||||
@@ -197,19 +164,19 @@ void loadPimInterProcessorLatencies(
|
||||
auto buffer = llvm::MemoryBuffer::getFile(networkPath);
|
||||
if (!buffer)
|
||||
llvm::report_fatal_error(
|
||||
llvm::Twine("failed to read Pim network config '")
|
||||
llvm::Twine("failed to read PIM network config '")
|
||||
+ networkPath + "': " + buffer.getError().message());
|
||||
auto parsed = llvm::json::parse(buffer.get()->getBuffer());
|
||||
if (!parsed)
|
||||
llvm::report_fatal_error(
|
||||
llvm::Twine("failed to parse Pim network config '")
|
||||
llvm::Twine("failed to parse PIM network config '")
|
||||
+ networkPath + "': " + llvm::toString(parsed.takeError()));
|
||||
const llvm::json::Object* root = parsed->getAsObject();
|
||||
const llvm::json::Object* latencies =
|
||||
root ? root->getObject("latency") : nullptr;
|
||||
if (!latencies)
|
||||
llvm::report_fatal_error(
|
||||
"Pim network config is missing its latency matrix");
|
||||
"PIM network config is missing its latency matrix");
|
||||
|
||||
target.interProcessorLatencyNs.assign(
|
||||
target.processorCount * target.processorCount, 0);
|
||||
@@ -220,7 +187,7 @@ void loadPimInterProcessorLatencies(
|
||||
const llvm::json::Object* row = latencies->getObject(sourceKey);
|
||||
if (!row)
|
||||
llvm::report_fatal_error(
|
||||
llvm::Twine("Pim network config is missing latency row ")
|
||||
llvm::Twine("PIM network config is missing latency row ")
|
||||
+ sourceKey);
|
||||
for (size_t destination = 0;
|
||||
destination < target.processorCount; ++destination) {
|
||||
@@ -230,7 +197,7 @@ void loadPimInterProcessorLatencies(
|
||||
std::optional<double> latency = row->getNumber(destinationKey);
|
||||
if (!latency || !std::isfinite(*latency) || *latency <= 0.0)
|
||||
llvm::report_fatal_error(
|
||||
llvm::Twine("Pim network config is missing latency ")
|
||||
llvm::Twine("PIM network config is missing latency ")
|
||||
+ sourceKey + " -> " + destinationKey);
|
||||
Cost roundedLatency = static_cast<Cost>(std::ceil(*latency));
|
||||
target.interProcessorLatencyNs[
|
||||
@@ -244,46 +211,27 @@ void loadPimInterProcessorLatencies(
|
||||
? 0
|
||||
: (latencySum + static_cast<Cost>(pairCount) - 1)
|
||||
/ static_cast<Cost>(pairCount);
|
||||
if (memorySwitch) {
|
||||
const auto *memoryRow = latencies->getObject(std::to_string(*memorySwitch));
|
||||
for (size_t core = 0; core < target.processorCount; ++core) {
|
||||
const auto *row = latencies->getObject(std::to_string(core));
|
||||
auto request = row ? row->getNumber(std::to_string(*memorySwitch)) : std::nullopt;
|
||||
auto response = memoryRow ? memoryRow->getNumber(std::to_string(core)) : std::nullopt;
|
||||
if (!request || !response || !std::isfinite(*request)
|
||||
|| !std::isfinite(*response) || *request < 0 || *response < 0
|
||||
|| *request >= static_cast<double>(std::numeric_limits<Cost>::max())
|
||||
|| *response >= static_cast<double>(std::numeric_limits<Cost>::max())) {
|
||||
target.sharedMemoryRequestLatencyNs.clear();
|
||||
target.sharedMemoryResponseLatencyNs.clear();
|
||||
break;
|
||||
}
|
||||
target.sharedMemoryRequestLatencyNs.push_back(std::ceil(*request));
|
||||
target.sharedMemoryResponseLatencyNs.push_back(std::ceil(*response));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PimInstructionTiming loadPimInstructionTiming() {
|
||||
PimInstructionTiming target;
|
||||
static_cast<spatial::SchedulingTarget &>(target) = getDefaultPimSchedulingTarget();
|
||||
spatial::SchedulingTarget getPimSchedulingTarget() {
|
||||
spatial::SchedulingTarget target = getDefaultPimSchedulingTarget();
|
||||
if (pimTargetConfig.empty())
|
||||
return target;
|
||||
|
||||
auto buffer = llvm::MemoryBuffer::getFile(pimTargetConfig);
|
||||
if (!buffer)
|
||||
llvm::report_fatal_error(
|
||||
llvm::Twine("failed to read Pim target config '")
|
||||
llvm::Twine("failed to read PIM target config '")
|
||||
+ pimTargetConfig.getValue() + "': " + buffer.getError().message());
|
||||
auto parsed = llvm::json::parse(buffer.get()->getBuffer());
|
||||
if (!parsed)
|
||||
llvm::report_fatal_error(
|
||||
llvm::Twine("failed to parse Pim target config '")
|
||||
llvm::Twine("failed to parse PIM target config '")
|
||||
+ pimTargetConfig.getValue() + "': "
|
||||
+ llvm::toString(parsed.takeError()));
|
||||
const llvm::json::Object* root = parsed->getAsObject();
|
||||
if (!root)
|
||||
llvm::report_fatal_error("Pim target config must contain a JSON object");
|
||||
llvm::report_fatal_error("PIM target config must contain a JSON object");
|
||||
|
||||
const llvm::json::Object& chip = requireObject(*root, "chip_config", "root");
|
||||
const llvm::json::Object& core = requireObject(chip, "core_config", "chip_config");
|
||||
@@ -293,22 +241,10 @@ PimInstructionTiming loadPimInstructionTiming() {
|
||||
requireObject(core, "local_memory_config", "chip_config.core_config");
|
||||
const llvm::json::Object& network =
|
||||
requireObject(chip, "network_config", "chip_config");
|
||||
// Older target configurations omit global memory and use adapter defaults.
|
||||
if (chip.get("global_memory_config")) {
|
||||
const llvm::json::Object& sharedMemory =
|
||||
requireObject(chip, "global_memory_config", "chip_config");
|
||||
Cost memoryPeriod = getConfigCost(sharedMemory, "period", Cost{1});
|
||||
target.sharedMemoryWidthBytes = getConfigCost(
|
||||
sharedMemory, "data_width", target.sharedMemoryWidthBytes);
|
||||
target.sharedMemoryReadLatencyNs = checkedMultiply(memoryPeriod,
|
||||
getConfigCost(sharedMemory, "read_latency_cycle", Cost{8}, true));
|
||||
target.sharedMemoryWriteLatencyNs = checkedMultiply(memoryPeriod,
|
||||
getConfigCost(sharedMemory, "write_latency_cycle", Cost{10}, true));
|
||||
}
|
||||
|
||||
std::optional<int64_t> coreCount = chip.getInteger("core_cnt");
|
||||
if (!coreCount || *coreCount <= 0)
|
||||
llvm::report_fatal_error("Pim target config field 'core_cnt' must be a positive integer");
|
||||
llvm::report_fatal_error("PIM target config field 'core_cnt' must be a positive integer");
|
||||
target.processorCount = static_cast<size_t>(*coreCount);
|
||||
target.residentWeightCapacity =
|
||||
getConfigCost(matrix, "xbar_array_count", target.residentWeightCapacity);
|
||||
@@ -319,21 +255,14 @@ PimInstructionTiming loadPimInstructionTiming() {
|
||||
|| target.residentWeightCapacity != crossbarCountInCore.getValue()
|
||||
|| target.matrixRows != crossbarSize.getValue()
|
||||
|| target.matrixColumns != crossbarSize.getValue())
|
||||
llvm::report_fatal_error("Pim target config resources do not match --core-count, "
|
||||
llvm::report_fatal_error("PIM target config resources do not match --core-count, "
|
||||
"--crossbar-count, and --crossbar-size");
|
||||
loadPimInterProcessorLatencies(target, network,
|
||||
core.getInteger("global_memory_switch_id"));
|
||||
loadPimInterProcessorLatencies(target, network);
|
||||
|
||||
target.processorPeriodNs =
|
||||
getConfigCost(core, "period", target.processorPeriodNs);
|
||||
target.signalIssueNs = target.processorPeriodNs;
|
||||
target.controlMessageBytes = 1;
|
||||
target.sharedMemoryReadReturnsPayload = false;
|
||||
target.peerPermissionThenSourceRead = true;
|
||||
target.localMemoryWidthBytes =
|
||||
getConfigCost(localMemory, "data_width", target.localMemoryWidthBytes);
|
||||
target.localMemoryPeriodNs =
|
||||
getConfigCost(localMemory, "period", target.localMemoryPeriodNs);
|
||||
target.localMemoryReadLatencyCycles =
|
||||
getConfigCost(localMemory, "read_latency_cycle", target.localMemoryReadLatencyCycles);
|
||||
target.localMemoryWriteLatencyCycles =
|
||||
@@ -375,77 +304,16 @@ PimInstructionTiming loadPimInstructionTiming() {
|
||||
|
||||
} // namespace
|
||||
|
||||
PimInstructionTiming getPimInstructionTiming() {
|
||||
return loadPimInstructionTiming();
|
||||
}
|
||||
|
||||
spatial::SchedulingTarget getPimSchedulingTarget() {
|
||||
auto timing = getPimInstructionTiming();
|
||||
auto target = static_cast<spatial::SchedulingTarget>(timing);
|
||||
configurePimScheduleCosts(target, std::move(timing));
|
||||
return target;
|
||||
}
|
||||
|
||||
llvm::Expected<int64_t> getPimPeriodicTimingContract() {
|
||||
auto buffer = llvm::MemoryBuffer::getFile(pimTargetConfig);
|
||||
if (!buffer) return llvm::createStringError("queue selection requires --pim-target-config with instruction timing");
|
||||
auto parsed = llvm::json::parse(buffer.get()->getBuffer());
|
||||
if (!parsed) return parsed.takeError();
|
||||
const auto *root = parsed->getAsObject();
|
||||
const auto *chip = root ? root->getObject("chip_config") : nullptr;
|
||||
const auto *core = chip ? chip->getObject("core_config") : nullptr;
|
||||
const auto *matrix = core ? core->getObject("matrix_config") : nullptr;
|
||||
if (!matrix || core->getInteger("rob_size").value_or(1) != 1)
|
||||
return llvm::createStringError("queue selection requires a target with ROB capacity one and matrix timing");
|
||||
auto bits = matrix->getInteger("cell_precision").value_or(2);
|
||||
if (bits <= 0) return llvm::createStringError("matrix cell precision must be positive");
|
||||
return bits;
|
||||
}
|
||||
|
||||
void addPimLoweringPasses(PassManager &pm,
|
||||
const spatial::SpatialTargetResources &targetResources, PimEmissionTargetType target,
|
||||
bool reportProgress) {
|
||||
auto message = [&](llvm::StringRef text) {
|
||||
if (reportProgress) pm.addPass(createMessagePass(text.str()));
|
||||
};
|
||||
if (target >= EmitPim) {
|
||||
pm.addPass(createSpatialToPimPass(targetResources));
|
||||
message("Spatial lowered to Pim");
|
||||
}
|
||||
|
||||
if (target >= EmitPimBufferized) {
|
||||
pm.addPass(createPimBufferizationPreparationPass(pimVerifyBufferizationCopyFreedom.getValue()));
|
||||
pm.addPass(createPimOneShotBufferizationPass());
|
||||
pm.addPass(createPimMemoryNormalizationPass());
|
||||
pm.addPass(createPimBufferizationVerificationPass());
|
||||
message("Pim bufferized");
|
||||
}
|
||||
|
||||
if (target >= EmitPimCodegen) {
|
||||
pm.addPass(mlir::createLowerAffinePass());
|
||||
pm.addPass(createPimHostConstantFoldingPass());
|
||||
message("Pim host constants folded");
|
||||
pm.addPass(createPimInstructionSelectionPass());
|
||||
message("Pim instructions selected");
|
||||
pm.addPass(createPimLocalMemoryPlanningPass());
|
||||
message("Pim local memory planned");
|
||||
pm.addPass(createPimVerificationPass(targetResources, pimDetectCommunicationDeadlock.getValue()));
|
||||
message("Pim verified");
|
||||
}
|
||||
}
|
||||
|
||||
void addPassesPim(OwningOpRef<ModuleOp>& module,
|
||||
PassManager& pm,
|
||||
EmissionTargetType& emissionTarget,
|
||||
std::string outputNameNoExt) {
|
||||
verifyPimCompilerOptions();
|
||||
spatial::SchedulingTarget schedulingTarget = getPimSchedulingTarget();
|
||||
spatial::SpatialTargetResources targetResources = getPimSpatialTargetResources(schedulingTarget);
|
||||
verifyExplicitPimCoreCount();
|
||||
|
||||
if (pimOnlyCodegen) {
|
||||
pm.addPass(createPimInstructionSelectionPass());
|
||||
pm.addPass(createPimLocalMemoryPlanningPass());
|
||||
pm.addPass(createPimVerificationPass(targetResources, pimDetectCommunicationDeadlock.getValue()));
|
||||
pm.addPass(createPimVerificationPass());
|
||||
pm.addPass(createEmitPimCodePass());
|
||||
return;
|
||||
}
|
||||
@@ -454,35 +322,44 @@ void addPassesPim(OwningOpRef<ModuleOp>& module,
|
||||
addONNXToMLIRPasses(pm, /*target CPU*/ false);
|
||||
|
||||
if (pimEmissionTarget >= EmitSpatial) {
|
||||
ONNXToSpatialPlanningOptions planningOptions = getPimONNXToSpatialPlanningOptions();
|
||||
spatial::SpatialDataflowExportStage exportStage =
|
||||
getPimSpatialDataflowExportStage(pimExportSpatialDataflow.getValue());
|
||||
pm.addPass(createONNXToSpatialPass(targetResources, planningOptions));
|
||||
pm.addPass(createSpatialLayoutPlanningPass(
|
||||
targetResources, pimDisableSpatialPlanning.getValue()));
|
||||
pm.addPass(createLowerSpatialPlansPass(targetResources, planningOptions, exportStage));
|
||||
spatial::SchedulingTarget schedulingTarget = getPimSchedulingTarget();
|
||||
spatial::SpatialTargetInfo targetInfo = getPimSpatialTargetInfo(schedulingTarget);
|
||||
pm.addPass(createONNXToSpatialPass(targetInfo));
|
||||
pm.addPass(createSpatialLayoutPlanningPass(targetInfo));
|
||||
pm.addPass(createLowerSpatialPlansPass(targetInfo));
|
||||
pm.addPass(createTrivialGraphComputeMergePass(
|
||||
schedulingTarget.residentWeightCapacity, exportStage));
|
||||
size_t stages = getPimPipelineStages();
|
||||
if (stages != 1 && pimEmissionTarget >= EmitPimCodegen) {
|
||||
pm.addPass(createPimPipelineSelectionPass(schedulingTarget, targetResources,
|
||||
stages, exportStage));
|
||||
pm.addPass(createEmitPimCodePass());
|
||||
return;
|
||||
} else {
|
||||
if (stages == 0) {
|
||||
llvm::report_fatal_error("--pipeline=auto requires full PIM code generation for queue-cost comparison");
|
||||
}
|
||||
if (stages > 1)
|
||||
pm.addPass(createMessagePass("Queue-aware pipeline: intermediate emission retains the original schedule without backend evaluation"));
|
||||
pm.addPass(spatial::createScheduleAndRealizeSpatialPass(
|
||||
schedulingTarget, exportStage, stages, pimPeriodicDiagnostics.getValue()));
|
||||
}
|
||||
schedulingTarget.residentWeightCapacity));
|
||||
auto scheduledState = std::make_shared<spatial::ScheduledSpatialState>();
|
||||
pm.addPass(spatial::createScheduleSpatialGraphPass(schedulingTarget, scheduledState));
|
||||
pm.addPass(spatial::createVerifyScheduledSpatialPass(scheduledState));
|
||||
pm.addPass(spatial::createRealizeSpatialCommunicationPass(schedulingTarget, scheduledState));
|
||||
pm.addPass(spatial::createVerifyRealizedSpatialPass(scheduledState));
|
||||
pm.addPass(createMessagePass("Onnx lowered to Spatial"));
|
||||
}
|
||||
|
||||
addPimLoweringPasses(pm, targetResources, pimEmissionTarget);
|
||||
if (pimEmissionTarget >= EmitPim) {
|
||||
pm.addPass(createSpatialToPimPass());
|
||||
pm.addPass(createMessagePass("Spatial lowered to Pim"));
|
||||
}
|
||||
|
||||
if (pimEmissionTarget >= EmitPimBufferized) {
|
||||
pm.addPass(createPimBufferizationPreparationPass());
|
||||
pm.addPass(createPimOneShotBufferizationPass());
|
||||
pm.addPass(createPimMemoryNormalizationPass());
|
||||
pm.addPass(createPimBufferizationVerificationPass());
|
||||
pm.addPass(createMessagePass("Pim bufferized"));
|
||||
}
|
||||
|
||||
if (pimEmissionTarget >= EmitPimCodegen) {
|
||||
pm.addPass(mlir::createLowerAffinePass());
|
||||
pm.addPass(createPimHostConstantFoldingPass());
|
||||
pm.addPass(createMessagePass("Pim host constants folded"));
|
||||
pm.addPass(createPimInstructionSelectionPass());
|
||||
pm.addPass(createMessagePass("Pim instructions selected"));
|
||||
pm.addPass(createPimLocalMemoryPlanningPass());
|
||||
pm.addPass(createMessagePass("Pim local memory planned"));
|
||||
pm.addPass(createPimVerificationPass());
|
||||
pm.addPass(createMessagePass("Pim verified"));
|
||||
pm.addPass(createEmitPimCodePass());
|
||||
pm.addPass(createMessagePass("Pim code emitted"));
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "mlir/IR/BuiltinOps.h"
|
||||
#include "llvm/Support/Error.h"
|
||||
#include "mlir/Pass/PassManager.h"
|
||||
#include "mlir/Pass/PassRegistry.h"
|
||||
|
||||
@@ -10,16 +8,6 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
namespace spatial { struct SchedulingTarget; struct SpatialTargetResources; }
|
||||
spatial::SchedulingTarget getPimSchedulingTarget();
|
||||
struct PimInstructionTiming;
|
||||
PimInstructionTiming getPimInstructionTiming();
|
||||
llvm::Expected<int64_t> getPimPeriodicTimingContract();
|
||||
|
||||
void addPimLoweringPasses(mlir::PassManager &pm,
|
||||
const spatial::SpatialTargetResources &resources, PimEmissionTargetType target,
|
||||
bool reportProgress = true);
|
||||
|
||||
void addPassesPim(mlir::OwningOpRef<mlir::ModuleOp>& module,
|
||||
mlir::PassManager& pm,
|
||||
EmissionTargetType& emissionTarget,
|
||||
|
||||
@@ -17,8 +17,6 @@ static FailureOr<CompiledCoreOpKind> classifyCompiledCoreOpKind(Operation& op) {
|
||||
if (isa<pim::PimVMVOp>(op)) return CompiledCoreOpKind::VMV;
|
||||
if (isa<pim::PimReceiveOp>(op)) return CompiledCoreOpKind::Receive;
|
||||
if (isa<pim::PimSendOp>(op)) return CompiledCoreOpKind::Send;
|
||||
if (isa<pim::PimWaitOp>(op)) return CompiledCoreOpKind::Wait;
|
||||
if (isa<pim::PimSyncOp>(op)) return CompiledCoreOpKind::Sync;
|
||||
if (isa<pim::PimConcatOp>(op)) return CompiledCoreOpKind::Concat;
|
||||
if (isa<pim::PimVMMOp>(op)) return CompiledCoreOpKind::Vmm;
|
||||
if (isa<pim::PimVVAddOp>(op)) return CompiledCoreOpKind::VVAdd;
|
||||
@@ -46,7 +44,7 @@ static LogicalResult compileCoreEmissionPlan(Block& block, SmallVectorImpl<Compi
|
||||
auto upper = compileIndexExpr(forOp.getUpperBound());
|
||||
auto step = compileIndexExpr(forOp.getStep());
|
||||
if (failed(lower) || failed(upper) || failed(step)) {
|
||||
forOp.emitOpError("requires statically evaluable scf.for bounds for Pim codegen");
|
||||
forOp.emitOpError("requires statically evaluable scf.for bounds for PIM codegen");
|
||||
return failure();
|
||||
}
|
||||
CompiledCoreNode node;
|
||||
@@ -63,7 +61,7 @@ static LogicalResult compileCoreEmissionPlan(Block& block, SmallVectorImpl<Compi
|
||||
if (auto ifOp = dyn_cast<scf::IfOp>(op)) {
|
||||
auto condition = compileIndexExpr(ifOp.getCondition());
|
||||
if (failed(condition)) {
|
||||
ifOp.emitOpError("requires statically evaluable scf.if condition for Pim codegen");
|
||||
ifOp.emitOpError("requires statically evaluable scf.if condition for PIM codegen");
|
||||
return failure();
|
||||
}
|
||||
CompiledCoreNode node;
|
||||
@@ -82,7 +80,7 @@ static LogicalResult compileCoreEmissionPlan(Block& block, SmallVectorImpl<Compi
|
||||
if (auto switchOp = dyn_cast<scf::IndexSwitchOp>(op)) {
|
||||
auto selector = compileIndexExpr(switchOp.getArg());
|
||||
if (failed(selector)) {
|
||||
switchOp.emitOpError("requires a statically evaluable scf.index_switch selector for Pim codegen");
|
||||
switchOp.emitOpError("requires a statically evaluable scf.index_switch selector for PIM codegen");
|
||||
return failure();
|
||||
}
|
||||
CompiledCoreNode node;
|
||||
|
||||
@@ -17,8 +17,6 @@ enum class CompiledCoreOpKind : uint8_t {
|
||||
VMV,
|
||||
Receive,
|
||||
Send,
|
||||
Wait,
|
||||
Sync,
|
||||
Concat,
|
||||
Vmm,
|
||||
VVAdd,
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
// Emptiness is normalized after consumption. Capacity and consumed prefixes
|
||||
// cannot affect virtual timing, readiness, or the remaining FIFO sequence.
|
||||
class PimDependencyTokens {
|
||||
llvm::SmallVector<uint64_t, 1> values;
|
||||
size_t head = 0;
|
||||
public:
|
||||
void initialize(size_t distance) { values.assign(distance, 0); head = 0; }
|
||||
bool empty() const { return values.empty(); }
|
||||
void push(uint64_t time) { values.push_back(time); }
|
||||
uint64_t consume() {
|
||||
assert(!empty());
|
||||
uint64_t time = values[head++];
|
||||
if (head == values.size()) { values.clear(); head = 0; }
|
||||
else if (head >= values.size() - head) {
|
||||
values.erase(values.begin(), values.begin() + head);
|
||||
head = 0;
|
||||
}
|
||||
return time;
|
||||
}
|
||||
llvm::ArrayRef<uint64_t> remaining() const { return llvm::ArrayRef(values).drop_front(head); }
|
||||
};
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,42 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
// PIM transport and instruction timing. Spatial consumes only the base costs.
|
||||
struct PimInstructionTiming : spatial::SchedulingTarget {
|
||||
Cost matrixCellBits = 0;
|
||||
bool peerPermissionThenSourceRead = false;
|
||||
Cost signalIssueNs = 0;
|
||||
Cost controlMessageBytes = 0;
|
||||
bool sharedMemoryReadReturnsPayload = true;
|
||||
std::vector<Cost> sharedMemoryRequestLatencyNs;
|
||||
std::vector<Cost> sharedMemoryResponseLatencyNs;
|
||||
|
||||
bool hasPeriodicTransferTiming() const {
|
||||
return processorCount && sharedMemoryWidthBytes && controlMessageBytes
|
||||
&& peerPermissionThenSourceRead
|
||||
&& sharedMemoryRequestLatencyNs.size() == processorCount
|
||||
&& sharedMemoryResponseLatencyNs.size() == processorCount
|
||||
&& interProcessorLatencyNs.size() == processorCount * processorCount
|
||||
&& localMemoryWidthBytes && transferWidthBytes;
|
||||
}
|
||||
|
||||
template <typename Arithmetic = SchedulingCostArithmetic>
|
||||
Cost getLinkServiceNs(Cost bytes, size_t source, size_t destination, Arithmetic math = {}) const {
|
||||
Cost flits = math.divideUp(bytes, transferWidthBytes);
|
||||
return math.multiply(flits,
|
||||
getInterProcessorLatencyNs(source, destination));
|
||||
}
|
||||
|
||||
template <typename Arithmetic = SchedulingCostArithmetic>
|
||||
Cost getSharedMemoryLinkServiceNs(Cost bytes, size_t core, bool response, Arithmetic math = {}) const {
|
||||
Cost flits = math.divideUp(bytes, transferWidthBytes);
|
||||
return math.multiply(flits, response ? sharedMemoryResponseLatencyNs[core]
|
||||
: sharedMemoryRequestLatencyNs[core]);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
} // namespace onnx_mlir
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,128 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace onnx_mlir {
|
||||
struct PimInstructionTiming;
|
||||
|
||||
enum class PimQueueTermination {
|
||||
NotRun, IntervalConverged, RecurrenceProved, EventBudget, GenerationLimit,
|
||||
HistoryLimit, NonMonotonic, NoReadyEvents
|
||||
};
|
||||
|
||||
struct PimQueueEventLocation {
|
||||
int64_t core = 0;
|
||||
uint32_t pc = 0;
|
||||
std::string kind;
|
||||
};
|
||||
|
||||
struct PimQueueProgress {
|
||||
size_t processedEvents = 0, completedGenerations = 0;
|
||||
uint64_t maximumQueueWaitNs = 0;
|
||||
std::optional<PimQueueEventLocation> maximumQueueRequest, generationLimit;
|
||||
std::vector<std::pair<int64_t, double>> perCoreQueueWaitNs;
|
||||
std::vector<uint64_t> completedIntervalsNs;
|
||||
};
|
||||
|
||||
struct PimQueueIntervalWindow {
|
||||
std::optional<double> intervalNs;
|
||||
std::string reason;
|
||||
PimQueueTermination termination = PimQueueTermination::NotRun;
|
||||
PimQueueProgress progress;
|
||||
};
|
||||
|
||||
struct PimQueuePolicyResult {
|
||||
PimQueueIntervalWindow legacy;
|
||||
spatial::ScheduleRecurrenceEvidence recurrence;
|
||||
PimQueueProgress progress;
|
||||
PimQueueTermination termination = PimQueueTermination::NotRun;
|
||||
size_t checkpoints = 0, historyBytes = 0, stateWords = 0, proofProcessedEvents = 0;
|
||||
bool reverseTies = false;
|
||||
std::optional<double> intervalNs() const;
|
||||
};
|
||||
|
||||
struct PimQueueEvaluation {
|
||||
std::array<PimQueuePolicyResult, 2> policies;
|
||||
uint64_t memoryServiceNs = 0;
|
||||
double evaluationSeconds = 0;
|
||||
bool recurrenceRequired = false, details = false, measureTime = false;
|
||||
spatial::WholeScheduleCost cost() const;
|
||||
};
|
||||
|
||||
llvm::json::Object serializePimQueueEvaluation(const PimQueueEvaluation &evaluation);
|
||||
|
||||
struct PimPeriodicEstimate {
|
||||
spatial::WholeScheduleCost cost;
|
||||
llvm::json::Object report;
|
||||
std::optional<PimQueueEvaluation> queue;
|
||||
};
|
||||
|
||||
// Binary instructions, indexed by physical core. No executable or measured data.
|
||||
struct PimInstructionProgram {
|
||||
std::vector<std::string> instructions;
|
||||
std::vector<std::vector<int64_t>> arrayGroups;
|
||||
};
|
||||
|
||||
// Hardware work only. Bytes are already in the target timing precision.
|
||||
// Repeat keeps ordered request patterns compact until queue construction.
|
||||
struct PimExecutionEvent {
|
||||
enum Kind { Work, Load, Store, Send, Receive, Signal, Wait, Repeat };
|
||||
enum WorkClass { Matrix, Vector, LocalCopy, Fill, VectorCopy, ScalarIssue };
|
||||
Kind kind = Work;
|
||||
uint64_t amount = 0;
|
||||
int64_t peer = 0, reg = 0, count = 0;
|
||||
std::vector<PimExecutionEvent> body;
|
||||
bool constant = false;
|
||||
WorkClass workClass = Fill;
|
||||
PimExecutionEvent(Kind kind, uint64_t amount, int64_t peer = 0,
|
||||
int64_t reg = 0, int64_t count = 0, std::vector<PimExecutionEvent> body = {})
|
||||
: kind(kind), amount(amount), peer(peer), reg(reg), count(count), body(std::move(body)) {}
|
||||
};
|
||||
using PimExecutionProgram = std::vector<std::vector<PimExecutionEvent>>;
|
||||
|
||||
struct PimPeriodicOptions {
|
||||
bool networkQueues = true;
|
||||
bool instructionIssue = true;
|
||||
bool scalarIssue = true;
|
||||
bool ignoreLocalCopies = false;
|
||||
// Spatial ablation mirrors codegen's omission of SYNC/WAIT instructions.
|
||||
bool omitSynchronization = false;
|
||||
bool workBreakdown = false;
|
||||
bool measureTime = false;
|
||||
bool searchGuidance = false;
|
||||
// Optional ordered work/IO extraction for timing validation; no execution.
|
||||
PimExecutionProgram *executionTrace = nullptr;
|
||||
// Prove recurrence of the modeled state. Instruction diagnostics retain
|
||||
// their legacy interval-window result separately.
|
||||
bool verifyPeriodicState = false;
|
||||
// Optional diagnostic cap. The complete-state proof keeps its original budget.
|
||||
std::optional<size_t> intervalWindowEventBudget;
|
||||
bool memoryController = true;
|
||||
bool detailed = false;
|
||||
// Apply the oracle's fp32-to-int8 timing projection without changing the program.
|
||||
bool oraclePrecision = false;
|
||||
};
|
||||
|
||||
llvm::json::Object analyzePimExecution(const PimExecutionProgram &program,
|
||||
const PimInstructionTiming &target, PimPeriodicOptions options = {});
|
||||
PimPeriodicEstimate evaluatePimExecution(const PimExecutionProgram &program,
|
||||
const PimInstructionTiming &target, PimPeriodicOptions options = {});
|
||||
|
||||
uint64_t getPimLocalTransferWorkNs(const PimInstructionTiming &target,
|
||||
uint64_t bytes, bool read, bool write, bool instructionIssue = true);
|
||||
uint64_t getPimVectorWorkNs(const PimInstructionTiming &target,
|
||||
uint64_t elements, uint64_t inputBytes, uint64_t outputBytes,
|
||||
bool binary, bool instructionIssue = true);
|
||||
uint64_t getPimMatrixOutputBytes(const PimInstructionTiming &target,
|
||||
uint64_t cellBits, uint64_t weightBits, uint64_t groups, uint64_t outputBytes);
|
||||
uint64_t getPimMatrixWorkNs(const PimInstructionTiming &target,
|
||||
uint64_t inputBits, uint64_t outputBytes, bool instructionIssue = true);
|
||||
|
||||
llvm::json::Object analyzePimInstructions(const PimInstructionProgram &program,
|
||||
const PimInstructionTiming &target, int64_t cellBits,
|
||||
PimPeriodicOptions options = {});
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,76 +0,0 @@
|
||||
#include "PimPeriodicAnalysis.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "PimCompilerUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
#include "llvm/Support/CommandLine.h"
|
||||
#include "llvm/Support/FormatVariadic.h"
|
||||
#include "llvm/Support/MemoryBuffer.h"
|
||||
#include <chrono>
|
||||
|
||||
using namespace onnx_mlir;
|
||||
namespace {
|
||||
llvm::cl::opt<std::string> artifact(llvm::cl::Positional, llvm::cl::Required,
|
||||
llvm::cl::desc("PIM binary artifact directory (native or oracle-exported)"));
|
||||
llvm::cl::opt<bool> queues("model-network-queues", llvm::cl::init(true));
|
||||
llvm::cl::opt<bool> issue("model-issue", llvm::cl::init(true));
|
||||
llvm::cl::opt<bool> oraclePrecision("oracle-precision", llvm::cl::init(false),
|
||||
llvm::cl::desc("Project native fp32 instructions to oracle int8 timing"));
|
||||
llvm::cl::opt<bool> memoryQueue("model-memory-controller", llvm::cl::init(false));
|
||||
llvm::Expected<llvm::json::Object> readJson(llvm::StringRef path) {
|
||||
auto buffer = llvm::MemoryBuffer::getFile(path);
|
||||
if (!buffer) return llvm::errorCodeToError(buffer.getError());
|
||||
auto parsed = llvm::json::parse(buffer.get()->getBuffer());
|
||||
if (!parsed) return parsed.takeError();
|
||||
if (!parsed->getAsObject()) return llvm::createStringError("expected a JSON object");
|
||||
return std::move(*parsed->getAsObject());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
llvm::cl::ParseCommandLineOptions(argc, argv, "Post-codegen periodic PIM diagnostics\n");
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
auto program = readJson(artifact + "/config.json");
|
||||
auto cellBits = getPimPeriodicTimingContract();
|
||||
if (!program || !cellBits) {
|
||||
llvm::errs() << (!program ? llvm::toString(program.takeError()) : llvm::toString(cellBits.takeError())) << '\n';
|
||||
return 1;
|
||||
}
|
||||
auto target = getPimInstructionTiming();
|
||||
PimInstructionProgram instructions;
|
||||
auto *groups = program->getObject("array_group_map");
|
||||
if (!groups) { llvm::errs() << "missing physical array groups\n"; return 1; }
|
||||
auto coreCount = program->getInteger("core_cnt");
|
||||
if (!coreCount || *coreCount <= 0 || *coreCount > static_cast<int64_t>(target.processorCount)) {
|
||||
llvm::errs() << "artifact core count does not fit the target\n"; return 1;
|
||||
}
|
||||
for (int64_t id = 0; id < *coreCount; ++id) {
|
||||
auto path = artifact + "/core_" + std::to_string(id) + ".pim";
|
||||
auto *array = groups->getArray("core" + std::to_string(id));
|
||||
if (!array) { llvm::errs() << "missing physical core array groups\n"; return 1; }
|
||||
auto buffer = llvm::MemoryBuffer::getFile(path);
|
||||
if (!buffer) { llvm::errs() << "cannot read instruction artifact\n"; return 1; }
|
||||
instructions.instructions.push_back(buffer.get()->getBuffer().str());
|
||||
std::vector<int64_t> counts;
|
||||
for (const auto &value : *array) {
|
||||
auto count = value.getAsInteger();
|
||||
if (!count) { llvm::errs() << "invalid array group\n"; return 1; }
|
||||
counts.push_back(*count);
|
||||
}
|
||||
instructions.arrayGroups.push_back(std::move(counts));
|
||||
}
|
||||
PimPeriodicOptions options;
|
||||
options.detailed = true;
|
||||
options.oraclePrecision = oraclePrecision;
|
||||
options.networkQueues = queues;
|
||||
options.instructionIssue = issue;
|
||||
options.memoryController = memoryQueue;
|
||||
auto report = analyzePimInstructions(instructions, target, *cellBits, options);
|
||||
report["diagnostic_only"] = true;
|
||||
report["selection_eligible"] = false;
|
||||
bool available = report.getString("status") == "estimated";
|
||||
report["analysis_wall_ms"] = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
llvm::outs() << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(report)));
|
||||
return available ? 0 : 1;
|
||||
}
|
||||
@@ -1,445 +0,0 @@
|
||||
#include "PimPipelineSelection.hpp"
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "PimCompilerUtils.hpp"
|
||||
#include "PimSpatialCost.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PipelineScheduling.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/DebugDump.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/FileSystemUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/ReportUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/ScheduledSpatialPasses.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/SpatialTargetResources.hpp"
|
||||
#include "mlir/Pass/PassManager.h"
|
||||
#include "mlir/Pass/PassInstrumentation.h"
|
||||
#include "src/Compiler/CompilerOptions.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ScheduleEvaluation.hpp"
|
||||
#include "llvm/Support/FormatVariadic.h"
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include "llvm/Support/raw_os_ostream.h"
|
||||
#include "src/Accelerators/PIM/Common/Support/Diagnostics.hpp"
|
||||
#include <chrono>
|
||||
#include <set>
|
||||
|
||||
using namespace mlir;
|
||||
using namespace onnx_mlir;
|
||||
using namespace onnx_mlir::spatial;
|
||||
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
double elapsed(Clock::time_point start) {
|
||||
return std::chrono::duration<double>(Clock::now() - start).count();
|
||||
}
|
||||
|
||||
llvm::json::Object countIR(Operation *root) {
|
||||
int64_t operations = 0, values = 0;
|
||||
root->walk([&](Operation *op) {
|
||||
++operations;
|
||||
values += op->getNumResults();
|
||||
for (Region ®ion : op->getRegions())
|
||||
for (Block &block : region) values += block.getNumArguments();
|
||||
});
|
||||
return llvm::json::Object{{"operations", operations}, {"values", values}};
|
||||
}
|
||||
|
||||
// Enabled with the existing compiler timing option. No instruction expansion.
|
||||
struct CandidateTiming final : PassInstrumentation {
|
||||
llvm::json::Object &summary;
|
||||
Clock::time_point start;
|
||||
explicit CandidateTiming(llvm::json::Object &summary) : summary(summary) {}
|
||||
void runBeforePass(Pass *pass, Operation *op) override {
|
||||
if (pass->getArgument() == "pim-one-shot-bufferization")
|
||||
summary["bufferization_input_ir"] = countIR(op);
|
||||
start = Clock::now();
|
||||
}
|
||||
void runAfterPass(Pass *pass, Operation *) override {
|
||||
auto *phases = summary.getObject("lowering_phases_seconds");
|
||||
if (!phases) {
|
||||
summary["lowering_phases_seconds"] = llvm::json::Object{};
|
||||
phases = summary.getObject("lowering_phases_seconds");
|
||||
}
|
||||
(*phases)[pass->getName()] = elapsed(start);
|
||||
}
|
||||
};
|
||||
|
||||
void writeSelectionReport(llvm::json::Object report) {
|
||||
auto file = openReportFileWithExtension("pipeline_selection", "json");
|
||||
if (file) {
|
||||
llvm::raw_os_ostream out(file);
|
||||
out << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(report)));
|
||||
}
|
||||
}
|
||||
|
||||
struct PimPipelineSelectionPass final : PassWrapper<PimPipelineSelectionPass, OperationPass<ModuleOp>> {
|
||||
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(PimPipelineSelectionPass)
|
||||
PimPipelineSelectionPass(const SchedulingTarget &target, const SpatialTargetResources &resources,
|
||||
size_t stages, SpatialDataflowExportStage exportStage)
|
||||
: target(target), resources(resources), stages(stages), exportStage(exportStage) {}
|
||||
SchedulingTarget target;
|
||||
SpatialTargetResources resources;
|
||||
size_t stages;
|
||||
SpatialDataflowExportStage exportStage;
|
||||
|
||||
StringRef getArgument() const override { return "pim-pipeline-selection"; }
|
||||
StringRef getDescription() const override { return "Select a throughput pipeline using static Spatial queue analysis"; }
|
||||
|
||||
LogicalResult realizeCandidate(ModuleOp checkpoint, const MergeScheduleResult &schedule,
|
||||
OwningOpRef<ModuleOp> &candidate, std::string &scheduleReport,
|
||||
llvm::json::Object &summary) {
|
||||
auto begin = Clock::now();
|
||||
IRMapping mapping;
|
||||
candidate = cast<ModuleOp>(checkpoint->clone(mapping));
|
||||
auto remapped = remapSpatialSchedule(schedule, mapping);
|
||||
if (failed(realizeSpatialSchedule(*candidate, remapped, target,
|
||||
stages ? stages : getPipelineStageCount(schedule),
|
||||
SpatialDataflowExportStage::None, nullptr, &scheduleReport))) return failure();
|
||||
summary["realization_seconds"] = elapsed(begin);
|
||||
return success();
|
||||
}
|
||||
|
||||
WholeScheduleCost spatialCost(ModuleOp candidate, llvm::json::Object &summary) {
|
||||
WholeScheduleCost cost;
|
||||
auto begin = Clock::now();
|
||||
llvm::json::Object estimate;
|
||||
if (target.estimateRealizedScheduleCost)
|
||||
cost = target.estimateRealizedScheduleCost(candidate, estimate);
|
||||
else cost.reason = target.wholeScheduleCostUnavailable.empty()
|
||||
? "target has no realized-Spatial cost query" : target.wholeScheduleCostUnavailable;
|
||||
cost.selectionMargin = kPipelineSelectionMargin;
|
||||
estimate["safe_for_selection"] = cost.eligible();
|
||||
estimate["diagnostic_only"] = false;
|
||||
summary["spatial_cost"] = std::move(estimate);
|
||||
summary["spatial_cost_seconds"] = elapsed(begin);
|
||||
return cost;
|
||||
}
|
||||
|
||||
LogicalResult evaluateSpatialCandidates(ModuleOp checkpoint,
|
||||
PreparedSpatialSchedules &prepared, std::vector<WholeScheduleCost> &costs,
|
||||
llvm::json::Object &report) {
|
||||
llvm::json::Array summaries;
|
||||
double realization = 0, extraction = 0, expansion = 0, queue = 0, evaluation = 0, dependency = 0;
|
||||
auto evaluate = [&](const MergeScheduleResult &schedule) {
|
||||
size_t index = summaries.size();
|
||||
llvm::json::Object summary{{"index", static_cast<int64_t>(index)}};
|
||||
OwningOpRef<ModuleOp> candidate;
|
||||
WholeScheduleCost cost;
|
||||
std::string scheduleReport;
|
||||
{
|
||||
ScopedCompilerOutputSuppression silence;
|
||||
if (failed(realizeCandidate(checkpoint, schedule, candidate, scheduleReport, summary)))
|
||||
cost.reason = "Spatial schedule realization failed verification";
|
||||
else cost = spatialCost(*candidate, summary);
|
||||
}
|
||||
realization += summary.getNumber("realization_seconds").value_or(0);
|
||||
evaluation += summary.getNumber("spatial_cost_seconds").value_or(0);
|
||||
extraction += cost.timing.extractionSeconds;
|
||||
expansion += cost.timing.expansionSeconds;
|
||||
queue += cost.timing.evaluationSeconds;
|
||||
dependency += cost.timing.dependencySeconds;
|
||||
auto convergence = cost.convergenceProved(), support = cost.loweringSupported();
|
||||
summary["cost_available"] = cost.available();
|
||||
summary["convergence_proved"] = convergence
|
||||
? llvm::json::Value(*convergence) : llvm::json::Value(nullptr);
|
||||
summary["lowering_supported"] = support
|
||||
? llvm::json::Value(*support) : llvm::json::Value(nullptr);
|
||||
summary["eligible"] = cost.eligible();
|
||||
if (cost.primary) summary["interval_ns"] = *cost.primary;
|
||||
if (cost.alternative) summary["alternative_tie_interval_ns"] = *cost.alternative;
|
||||
llvm::json::Array budgets, witness;
|
||||
size_t depth = getPipelineStageCount(schedule);
|
||||
std::vector<size_t> cores(depth);
|
||||
std::vector<double> pressure(depth);
|
||||
std::vector<bool> active(depth);
|
||||
for (const auto &[instance, core] : schedule.computeToCpuMap)
|
||||
active[schedule.processorStages.empty() ? 0 : schedule.processorStages[core]] = true;
|
||||
summary["active_stage_count"] = static_cast<int64_t>(llvm::count(active, true));
|
||||
for (size_t core = 0; core < schedule.processorCount; ++core) {
|
||||
size_t stage = schedule.processorStages.empty() ? 0 : schedule.processorStages[core];
|
||||
++cores[stage];
|
||||
if (core < cost.processorCriticalDelayNs.size())
|
||||
pressure[stage] += cost.processorCriticalDelayNs[core];
|
||||
}
|
||||
for (size_t stage = 0; stage < depth; ++stage) {
|
||||
budgets.push_back(static_cast<int64_t>(cores[stage]));
|
||||
witness.push_back(pressure[stage]);
|
||||
}
|
||||
summary["stage_core_budgets"] = std::move(budgets);
|
||||
summary["recurrence_stage_contributions_ns"] = std::move(witness);
|
||||
llvm::json::Array runs;
|
||||
for (size_t begin = 0; begin < prepared.graph.nodes.size();) {
|
||||
auto stageFor = [&](size_t task) {
|
||||
return schedule.processorStages.empty() ? size_t{0}
|
||||
: schedule.processorStages[schedule.computeToCpuMap.lookup(prepared.graph.nodes[task].instance)];
|
||||
};
|
||||
size_t end = begin + 1, stage = stageFor(begin);
|
||||
while (end < prepared.graph.nodes.size() && stageFor(end) == stage) ++end;
|
||||
runs.push_back(llvm::json::Array{static_cast<int64_t>(begin),
|
||||
static_cast<int64_t>(end - begin), static_cast<int64_t>(stage)});
|
||||
begin = end;
|
||||
}
|
||||
summary["task_stage_runs"] = std::move(runs);
|
||||
if (!cost.eligible()) summary["reason"] = cost.reason;
|
||||
summaries.push_back(std::move(summary));
|
||||
return cost;
|
||||
};
|
||||
std::string error;
|
||||
auto start = Clock::now();
|
||||
auto search = optimizePipelineSchedule(prepared.graph, prepared.candidates.front(),
|
||||
stages, target, evaluate, error);
|
||||
report["search_seconds"] = elapsed(start);
|
||||
report["search_refinement_seconds"] = std::max(0.0, elapsed(start) - realization - evaluation);
|
||||
report["cost_evaluation_seconds"] = evaluation;
|
||||
report["candidate_realization_seconds"] = realization;
|
||||
report["event_extraction_seconds"] = extraction;
|
||||
report["event_expansion_seconds"] = expansion;
|
||||
report["queue_seconds"] = queue;
|
||||
report["dependency_analysis_seconds"] = dependency;
|
||||
report["candidates"] = std::move(summaries);
|
||||
if (failed(search)) {
|
||||
report["status"] = "incomplete-costs";
|
||||
report["reason"] = error;
|
||||
checkpoint.emitError("Spatial pipeline cannot compare the complete candidate set: ") << error;
|
||||
return failure();
|
||||
}
|
||||
prepared.candidates = std::move(search->schedules);
|
||||
costs = std::move(search->costs);
|
||||
bool single = costs.empty();
|
||||
if (single) {
|
||||
report["candidates"] = llvm::json::Array{llvm::json::Object{{"index", 0},
|
||||
{"active_stage_count", static_cast<int64_t>(getPipelineStageCount(prepared.candidates.front()))}}};
|
||||
} else {
|
||||
auto *entries = report.getArray("candidates");
|
||||
for (size_t i = 0; i < entries->size(); ++i) {
|
||||
auto &entry = *(*entries)[i].getAsObject();
|
||||
entry["parent"] = static_cast<int64_t>(search->parents[i]);
|
||||
entry["expansions"] = static_cast<int64_t>(search->expansions[i]);
|
||||
entry["origin"] = i < search->initialSchedules ? "depth-initialization" : "refinement";
|
||||
}
|
||||
}
|
||||
report["generated_candidates"] = static_cast<int64_t>(prepared.candidates.size());
|
||||
report["single_candidate_analysis_skipped"] = single;
|
||||
report["search_rounds"] = static_cast<int64_t>(search->rounds);
|
||||
report["packing_attempts"] = static_cast<int64_t>(search->packingAttempts);
|
||||
report["neighborhood_seconds"] = search->neighborhoodSeconds;
|
||||
report["constructive_packing_seconds"] = search->packingSeconds;
|
||||
report["considered_assignments"] = static_cast<int64_t>(search->consideredAssignments);
|
||||
report["search_termination"] = search->termination;
|
||||
report["queue_evaluation_budget"] = static_cast<int64_t>(kPipelineQueueEvaluationBudget);
|
||||
report["beam_width"] = static_cast<int64_t>(kPipelineBeamWidth);
|
||||
report["maximum_depth"] = static_cast<int64_t>(search->maximumDepth);
|
||||
report["grouping_seconds"] = search->groupingSeconds;
|
||||
report["initialization_segment_seconds"] = search->segmentCostSeconds;
|
||||
report["initialization_dp_seconds"] = search->partitionStateSeconds;
|
||||
report["initialization_placement_seconds"] = search->initializationPlacementSeconds;
|
||||
report["initialization_packing_queries"] = static_cast<int64_t>(search->initializationPackingQueries);
|
||||
report["initialization_dp_transitions"] = static_cast<int64_t>(search->partitionTransitions);
|
||||
report["initialization_ordered_threshold_scans"] = static_cast<int64_t>(search->orderedThresholdScans);
|
||||
llvm::json::Array priorities;
|
||||
for (auto [depth, priority] : search->depthPriorities)
|
||||
priorities.push_back(llvm::json::Object{{"depth", static_cast<int64_t>(depth)},
|
||||
{"priority", static_cast<double>(priority)}});
|
||||
report["depth_priorities"] = std::move(priorities);
|
||||
report["frontier_policy"] = "incumbent-plus-bounded-lookahead-best-first";
|
||||
if (!prepared.latencyInitializationReason.empty())
|
||||
report["latency_initialization_reason"] = prepared.latencyInitializationReason;
|
||||
llvm::json::Array explored;
|
||||
std::set<size_t> depths;
|
||||
for (const auto &schedule : prepared.candidates) depths.insert(getPipelineStageCount(schedule));
|
||||
for (size_t depth : depths) explored.push_back(static_cast<int64_t>(depth));
|
||||
report["explored_depths"] = std::move(explored);
|
||||
llvm::json::Array domain;
|
||||
for (size_t depth = stages ? stages : 1; depth <= search->maximumDepth; ++depth) {
|
||||
size_t count = llvm::count_if(prepared.candidates, [&](const auto &schedule) {
|
||||
return getPipelineStageCount(schedule) == depth;
|
||||
});
|
||||
llvm::json::Object entry{{"depth", static_cast<int64_t>(depth)},
|
||||
{"evaluated_schedules", static_cast<int64_t>(single ? 0 : count)},
|
||||
{"status", count ? (single ? "initialized-single-schedule" : "queue-validated") : "not-explored"}};
|
||||
for (const auto &[failedDepth, reason] : search->depthInitializationFailures)
|
||||
if (depth == failedDepth && !count) { entry["status"] = "initialization-failed"; entry["reason"] = reason; }
|
||||
if (depth == 1 && !prepared.latencyInitializationReason.empty()) {
|
||||
entry["status"] = "initialization-failed";
|
||||
entry["reason"] = prepared.latencyInitializationReason;
|
||||
}
|
||||
domain.push_back(std::move(entry));
|
||||
}
|
||||
report["depth_search"] = std::move(domain);
|
||||
return success();
|
||||
}
|
||||
|
||||
void runOnOperation() override {
|
||||
ModuleOp checkpoint = getOperation();
|
||||
auto start = Clock::now();
|
||||
auto prepared = prepareSpatialSchedules(checkpoint, target, stages);
|
||||
if (failed(prepared)) { signalPassFailure(); return; }
|
||||
if (prepared->candidates.empty()) {
|
||||
checkpoint.emitError("Spatial pipeline requires at least one candidate schedule");
|
||||
signalPassFailure(); return;
|
||||
}
|
||||
llvm::json::Object report{{"strategy", "spatial-queue-aware"}, {"static_analysis", true},
|
||||
{"candidate_generation_seconds", elapsed(start)},
|
||||
{"generated_candidates", static_cast<int64_t>(prepared->candidates.size())},
|
||||
{"selection_margin", kPipelineSelectionMargin},
|
||||
{"prediction_error_bound_available", false}, {"temporary_disk_bytes", 0}};
|
||||
report["requested_depth"] = stages ? llvm::json::Value(static_cast<int64_t>(stages))
|
||||
: llvm::json::Value("auto");
|
||||
if (pimDisableSynchronization) {
|
||||
report["synchronization_ablation"] = true;
|
||||
report["cost_model_program"] = "synchronized-reference";
|
||||
llvm::errs() << "Synchronization ablation: keep the normal selected schedule; "
|
||||
"report zero-cost SYNC/WAIT separately and omit them in code generation. "
|
||||
"Buffer reuse and restart correctness are not guaranteed.\n";
|
||||
}
|
||||
std::vector<WholeScheduleCost> costs;
|
||||
if (failed(evaluateSpatialCandidates(checkpoint, *prepared, costs, report))) {
|
||||
writeSelectionReport(std::move(report)); signalPassFailure(); return;
|
||||
}
|
||||
bool single = costs.empty();
|
||||
OwningOpRef<ModuleOp> winner;
|
||||
std::string scheduleReport;
|
||||
llvm::json::Array attempts;
|
||||
double realizationSeconds = 0, backendSeconds = 0;
|
||||
size_t lowered = 0;
|
||||
auto attempt = [&](size_t index) {
|
||||
llvm::json::Object summary{{"candidate", static_cast<int64_t>(index)}};
|
||||
std::string capturedReport;
|
||||
OwningOpRef<ModuleOp> candidate;
|
||||
LogicalResult realized = failure();
|
||||
{
|
||||
ScopedCompilerOutputSuppression silence;
|
||||
realized = realizeCandidate(checkpoint, prepared->candidates[index], candidate, capturedReport, summary);
|
||||
}
|
||||
PimCandidateResult result = PimCandidateResult::Failure;
|
||||
if (failed(realized)) {
|
||||
summary["reason"] = "selected Spatial schedule failed deterministic realization";
|
||||
summary["status"] = "realization-failed";
|
||||
} else {
|
||||
if (pimDisableSynchronization)
|
||||
summary["synchronization_ablation_cost"] = analyzePimSpatialSynchronizationAblation(*candidate);
|
||||
++lowered;
|
||||
result = lowerPimPipelineCandidate(*candidate, resources, summary);
|
||||
}
|
||||
realizationSeconds += summary.getNumber("realization_seconds").value_or(0);
|
||||
backendSeconds += summary.getNumber("backend_seconds").value_or(0);
|
||||
if (result == PimCandidateResult::Success) {
|
||||
summary["status"] = "lowered";
|
||||
winner = std::move(candidate);
|
||||
scheduleReport = std::move(capturedReport);
|
||||
} else if (result == PimCandidateResult::ResourceLimit)
|
||||
llvm::errs() << "Spatial pipeline candidate " << index
|
||||
<< " rejected by a backend resource limit; rejection recorded in pipeline_selection.json\n";
|
||||
attempts.push_back(std::move(summary));
|
||||
return result;
|
||||
};
|
||||
std::string reason;
|
||||
std::optional<size_t> selected;
|
||||
if (single) {
|
||||
if (attempt(0) == PimCandidateResult::Success) selected = 0;
|
||||
reason = selected ? "one distinct schedule; no cost comparison required"
|
||||
: "the single schedule failed backend lowering; no alternatives are available";
|
||||
} else selected = lowerSelectedPimCandidate(costs, attempt, reason);
|
||||
report["backend_attempts"] = std::move(attempts);
|
||||
report["lowered_candidates"] = static_cast<int64_t>(lowered);
|
||||
report["costed_candidates"] = single ? 0 : static_cast<int64_t>(costs.size());
|
||||
size_t attemptCount = report.getArray("backend_attempts")->size();
|
||||
report["backend_retries"] = static_cast<int64_t>(attemptCount ? attemptCount - 1 : 0);
|
||||
report["winner_realization_seconds"] = realizationSeconds;
|
||||
report["backend_lowering_seconds"] = backendSeconds;
|
||||
if (!selected) {
|
||||
report["status"] = "backend-failure";
|
||||
report["reason"] = reason;
|
||||
std::string failures;
|
||||
for (auto &entry : *report.getArray("backend_attempts")) {
|
||||
auto *failed = entry.getAsObject();
|
||||
failures += "\ncandidate " + std::to_string(*failed->getInteger("candidate"))
|
||||
+ ": " + failed->getString("reason").value_or("backend failure").str();
|
||||
}
|
||||
checkpoint.emitError("Spatial pipeline backend selection failed; ") << reason << failures;
|
||||
writeSelectionReport(std::move(report)); signalPassFailure(); return;
|
||||
}
|
||||
auto finalize = Clock::now();
|
||||
bool spatialArtifacts = exportStage != SpatialDataflowExportStage::None
|
||||
|| pimPeriodicDiagnostics || isPimIrDumpEnabled();
|
||||
if (spatialArtifacts) {
|
||||
if (failed(realizeSpatialSchedule(checkpoint, prepared->candidates[*selected], target,
|
||||
stages ? stages : getPipelineStageCount(prepared->candidates[*selected]),
|
||||
exportStage, pimPeriodicDiagnostics ? &prepared->graph : nullptr))) {
|
||||
signalPassFailure(); return;
|
||||
}
|
||||
} else {
|
||||
auto file = openDialectDumpFileWithExtension("spatial3_scheduled_no_comm", "/reports", "txt");
|
||||
if (file) file << scheduleReport;
|
||||
}
|
||||
checkpoint->setAttrs((*winner)->getAttrs());
|
||||
checkpoint.getBodyRegion().takeBody(winner->getBodyRegion());
|
||||
report["selection"] = static_cast<int64_t>(*selected);
|
||||
report["selected_depth"] = static_cast<int64_t>(getPipelineStageCount(prepared->candidates[*selected]));
|
||||
report["status"] = "selected";
|
||||
report["reason"] = reason;
|
||||
report["finalization_seconds"] = elapsed(finalize);
|
||||
report["total_seconds"] = elapsed(start);
|
||||
llvm::errs() << "Spatial queue-aware pipeline: candidate " << *selected << " of " << prepared->candidates.size()
|
||||
<< "; " << reason << "\n";
|
||||
writeSelectionReport(std::move(report));
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
PimCandidateResult onnx_mlir::lowerPimPipelineCandidate(ModuleOp module,
|
||||
const SpatialTargetResources &resources, llvm::json::Object &summary) {
|
||||
bool classified = true, anyError = false;
|
||||
std::string diagnostic;
|
||||
size_t count = 0;
|
||||
ScopedDiagnosticHandler handler(module.getContext(), [&](Diagnostic &message) {
|
||||
if (message.getSeverity() == DiagnosticSeverity::Error) {
|
||||
anyError = true;
|
||||
classified &= pim::isCandidateResourceError(message);
|
||||
if (++count <= 8) diagnostic += message.str().substr(0, 2048) + "\n";
|
||||
}
|
||||
return success();
|
||||
});
|
||||
auto start = Clock::now();
|
||||
PassManager pm(module.getContext());
|
||||
addPimLoweringPasses(pm, resources, EmitPimCodegen, /*reportProgress=*/false);
|
||||
if (enableTiming) pm.addInstrumentation(std::make_unique<CandidateTiming>(summary));
|
||||
LogicalResult result = pm.run(module);
|
||||
summary["backend_seconds"] = elapsed(start);
|
||||
if (succeeded(result)) return PimCandidateResult::Success;
|
||||
summary["reason"] = diagnostic.empty() ? "backend failed without a classified diagnostic" : diagnostic;
|
||||
bool resource = anyError && classified;
|
||||
summary["status"] = resource ? "resource-limit" : "systemic-or-unclassified-error";
|
||||
return resource ? PimCandidateResult::ResourceLimit : PimCandidateResult::Failure;
|
||||
}
|
||||
|
||||
std::optional<size_t> onnx_mlir::lowerSelectedPimCandidate(llvm::ArrayRef<WholeScheduleCost> costs,
|
||||
const std::function<PimCandidateResult(size_t)> &lower, std::string &reason) {
|
||||
if (costs.empty()) {
|
||||
reason = "Spatial pipeline requires at least one candidate schedule";
|
||||
return std::nullopt;
|
||||
}
|
||||
for (const auto &cost : costs)
|
||||
if (!cost.eligible()) {
|
||||
reason = "cannot compare the complete candidate set: unavailable cost or unproved eligibility";
|
||||
return std::nullopt;
|
||||
}
|
||||
std::vector<WholeScheduleCost> remaining(costs.begin(), costs.end());
|
||||
std::vector<size_t> indices;
|
||||
for (size_t i = 0; i < costs.size(); ++i) indices.push_back(i);
|
||||
while (!indices.empty()) {
|
||||
size_t selected = selectPipelineCandidate(remaining, reason);
|
||||
auto result = lower(indices[selected]);
|
||||
if (result == PimCandidateResult::Success) return indices[selected];
|
||||
if (result != PimCandidateResult::ResourceLimit) {
|
||||
reason = "systemic or unclassified backend failure; recovery is not justified";
|
||||
return std::nullopt;
|
||||
}
|
||||
remaining.erase(remaining.begin() + selected);
|
||||
indices.erase(indices.begin() + selected);
|
||||
}
|
||||
reason = "all candidate schedules failed backend resource constraints";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::unique_ptr<Pass> onnx_mlir::createPimPipelineSelectionPass(
|
||||
const SchedulingTarget &target, const SpatialTargetResources &resources,
|
||||
size_t stages, SpatialDataflowExportStage exportStage) {
|
||||
return std::make_unique<PimPipelineSelectionPass>(target, resources, stages, exportStage);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
#include "mlir/Pass/Pass.h"
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace mlir { class ModuleOp; }
|
||||
namespace llvm::json { class Object; }
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace spatial { struct SchedulingTarget; struct SpatialTargetResources; struct WholeScheduleCost; enum class SpatialDataflowExportStage; }
|
||||
enum class PimCandidateResult { Success, ResourceLimit, Failure };
|
||||
PimCandidateResult lowerPimPipelineCandidate(mlir::ModuleOp module,
|
||||
const spatial::SpatialTargetResources &resources, llvm::json::Object &summary);
|
||||
// Callback failures distinguish owner-classified resource limits from other errors.
|
||||
std::optional<size_t> lowerSelectedPimCandidate(llvm::ArrayRef<spatial::WholeScheduleCost> costs,
|
||||
const std::function<PimCandidateResult(size_t)> &lower, std::string &reason);
|
||||
std::unique_ptr<mlir::Pass> createPimPipelineSelectionPass(
|
||||
const spatial::SchedulingTarget &target, const spatial::SpatialTargetResources &resources,
|
||||
size_t stages, spatial::SpatialDataflowExportStage exportStage);
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,125 +0,0 @@
|
||||
#include "PimPeriodicAnalysis.hpp"
|
||||
|
||||
using namespace onnx_mlir;
|
||||
|
||||
namespace {
|
||||
const char *windowStatus(const PimQueuePolicyResult &policy) {
|
||||
if (policy.legacy.intervalNs) return "estimated";
|
||||
return policy.legacy.termination == PimQueueTermination::NotRun && policy.recurrence.proved()
|
||||
? "not-required" : "unavailable";
|
||||
}
|
||||
|
||||
const char *terminationName(PimQueueTermination termination) {
|
||||
switch (termination) {
|
||||
case PimQueueTermination::NotRun: return "not-run";
|
||||
case PimQueueTermination::IntervalConverged: return "interval-converged";
|
||||
case PimQueueTermination::RecurrenceProved: return "recurrence-proved";
|
||||
case PimQueueTermination::EventBudget: return "event-budget";
|
||||
case PimQueueTermination::GenerationLimit: return "generation-limit";
|
||||
case PimQueueTermination::HistoryLimit: return "history-limit";
|
||||
case PimQueueTermination::NonMonotonic: return "non-monotonic";
|
||||
case PimQueueTermination::NoReadyEvents: return "no-ready-events";
|
||||
}
|
||||
llvm_unreachable("invalid queue termination");
|
||||
}
|
||||
|
||||
void serializeProgress(llvm::json::Object &report, const PimQueueProgress &progress,
|
||||
bool estimated, bool details, bool intervals) {
|
||||
if (progress.processedEvents) report["processed_events"] = progress.processedEvents;
|
||||
if (estimated) {
|
||||
report["completed_generations"] = progress.completedGenerations;
|
||||
report["maximum_queue_wait_ns_including_bootstrap"] = progress.maximumQueueWaitNs;
|
||||
if (progress.maximumQueueRequest) {
|
||||
report["maximum_queue_core"] = progress.maximumQueueRequest->core;
|
||||
report["maximum_queue_pc"] = progress.maximumQueueRequest->pc;
|
||||
}
|
||||
if (details) {
|
||||
llvm::json::Array cores;
|
||||
for (auto [core, wait] : progress.perCoreQueueWaitNs)
|
||||
cores.push_back(llvm::json::Object{{"core", core}, {"queue_wait_ns", wait}});
|
||||
report["per_core"] = std::move(cores);
|
||||
}
|
||||
}
|
||||
if (progress.generationLimit) {
|
||||
report["generation_limit_core"] = progress.generationLimit->core;
|
||||
report["generation_limit_pc"] = progress.generationLimit->pc;
|
||||
report["generation_limit_kind"] = progress.generationLimit->kind;
|
||||
}
|
||||
if (intervals) {
|
||||
llvm::json::Array values;
|
||||
for (uint64_t value : progress.completedIntervalsNs) values.push_back(value);
|
||||
report["completed_interval_ns"] = std::move(values);
|
||||
}
|
||||
}
|
||||
|
||||
llvm::json::Object serializeWindow(const PimQueuePolicyResult &policy, bool details) {
|
||||
const auto &window = policy.legacy;
|
||||
llvm::json::Object result{{"status", windowStatus(policy)}};
|
||||
if (window.intervalNs) {
|
||||
result["interval_ns"] = *window.intervalNs;
|
||||
result["tie_policy"] = policy.reverseTies ? "reverse event-index order for simultaneous readiness"
|
||||
: "event-index order for simultaneous readiness";
|
||||
}
|
||||
if (!window.reason.empty()) result["reason"] = window.reason;
|
||||
serializeProgress(result, window.progress, window.intervalNs.has_value(), details,
|
||||
window.termination == PimQueueTermination::EventBudget
|
||||
|| window.termination == PimQueueTermination::NoReadyEvents);
|
||||
return result;
|
||||
}
|
||||
|
||||
llvm::json::Object serializeRecurrence(const PimQueuePolicyResult &policy) {
|
||||
const auto &evidence = policy.recurrence;
|
||||
llvm::json::Object result{{"status", evidence.proved() ? "proved" : "unproved"},
|
||||
{"termination", terminationName(policy.termination)}};
|
||||
if (policy.checkpoints) {
|
||||
result["checkpoints"] = policy.checkpoints;
|
||||
result["history_bytes"] = policy.historyBytes;
|
||||
}
|
||||
if (evidence.proved()) {
|
||||
result["period_generations"] = evidence.periodGenerations;
|
||||
result["interval_ns"] = *evidence.intervalNs;
|
||||
result["state_words"] = policy.stateWords;
|
||||
result["complete_scheduler_state"] = true;
|
||||
result["proof_processed_events"] = policy.proofProcessedEvents;
|
||||
}
|
||||
if (!evidence.reason.empty()) result["reason"] = evidence.reason;
|
||||
return result;
|
||||
}
|
||||
|
||||
void addAlternative(llvm::json::Object &report, const PimQueuePolicyResult &policy, bool legacy) {
|
||||
auto interval = legacy ? policy.legacy.intervalNs : policy.intervalNs();
|
||||
report["alternative_tie_status"] = legacy ? windowStatus(policy) : interval ? "estimated" : "unavailable";
|
||||
if (interval) report["alternative_tie_interval_ns"] = *interval;
|
||||
if ((legacy || !policy.recurrence.proved()) && !policy.legacy.reason.empty())
|
||||
report["alternative_tie_reason"] = policy.legacy.reason;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
llvm::json::Object onnx_mlir::serializePimQueueEvaluation(const PimQueueEvaluation &evaluation) {
|
||||
const auto &primary = evaluation.policies[0];
|
||||
const auto &alternative = evaluation.policies[1];
|
||||
llvm::json::Object report;
|
||||
if (evaluation.recurrenceRequired && primary.recurrence.proved()) {
|
||||
report = llvm::json::Object{{"status", "estimated"}, {"interval_ns", *primary.intervalNs()},
|
||||
{"tie_policy", primary.reverseTies ? "reverse event-index order for simultaneous readiness"
|
||||
: "event-index order for simultaneous readiness"}};
|
||||
serializeProgress(report, primary.progress, true, evaluation.details, false);
|
||||
} else report = serializeWindow(primary, evaluation.details);
|
||||
if (evaluation.recurrenceRequired) {
|
||||
auto legacy = serializeWindow(primary, evaluation.details);
|
||||
legacy["termination"] = terminationName(primary.legacy.termination);
|
||||
legacy["alternative_termination"] = terminationName(alternative.legacy.termination);
|
||||
addAlternative(legacy, alternative, true);
|
||||
report["interval_source"] = primary.recurrence.proved() ? "complete-state recurrence" : "legacy interval window";
|
||||
report["alternative_interval_source"] = alternative.recurrence.proved() ? "complete-state recurrence" : "legacy interval window";
|
||||
report["periodic_state"] = serializeRecurrence(primary);
|
||||
report["alternative_periodic_state"] = serializeRecurrence(alternative);
|
||||
report["legacy_interval_window"] = std::move(legacy);
|
||||
}
|
||||
addAlternative(report, alternative, false);
|
||||
if (auto interval = primary.intervalNs())
|
||||
report["memory_service_fraction"] = evaluation.memoryServiceNs / *interval;
|
||||
if (evaluation.measureTime) report["analysis_ms"] = evaluation.evaluationSeconds * 1000;
|
||||
report["arbitration"] = "FIFO by predicted controller arrival";
|
||||
return report;
|
||||
}
|
||||
@@ -1,468 +0,0 @@
|
||||
#include "PimScheduleDiagnostic.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredTransferPlanning.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PeriodicDependencies.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/DebugDump.hpp"
|
||||
|
||||
#include "llvm/ADT/MapVector.h"
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include "llvm/Support/raw_os_ostream.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
|
||||
namespace onnx_mlir {
|
||||
using namespace spatial;
|
||||
namespace {
|
||||
|
||||
struct Event {
|
||||
int64_t core;
|
||||
llvm::StringRef kind;
|
||||
int64_t identity;
|
||||
};
|
||||
struct DirectEndpoint {
|
||||
size_t begin;
|
||||
size_t end;
|
||||
int64_t core;
|
||||
Cost bytes;
|
||||
};
|
||||
struct Signal {
|
||||
size_t event;
|
||||
int64_t core;
|
||||
};
|
||||
struct Wait {
|
||||
size_t event;
|
||||
int64_t count;
|
||||
};
|
||||
using Register = std::pair<int64_t, unsigned>;
|
||||
|
||||
class PeriodicPlan {
|
||||
public:
|
||||
PeriodicPlan(const PimInstructionTiming &target,
|
||||
const DeferredTransferPlan &transfers)
|
||||
: target(target), transfers(transfers), computeWork(target.processorCount),
|
||||
entry(target.processorCount), tail(target.processorCount),
|
||||
active(target.processorCount) {}
|
||||
|
||||
bool build(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredBoundaryPlan &boundaries);
|
||||
|
||||
const PimInstructionTiming ⌖
|
||||
const DeferredTransferPlan &transfers;
|
||||
std::vector<Event> events;
|
||||
std::vector<PeriodicDependency> edges;
|
||||
SharedMemoryDemand boundaryMemory;
|
||||
std::vector<Cost> computeWork;
|
||||
std::string error;
|
||||
void recordSynchronization(llvm::json::Object &report) const;
|
||||
|
||||
private:
|
||||
size_t event(int64_t core, llvm::StringRef kind, int64_t identity = -1) {
|
||||
events.push_back({core, kind, identity});
|
||||
return events.size() - 1;
|
||||
}
|
||||
size_t append(int64_t core, llvm::StringRef kind, Cost delay = 0,
|
||||
int64_t identity = -1) {
|
||||
size_t next = event(core, kind, identity);
|
||||
edges.push_back({tail[core], next, delay, 0});
|
||||
tail[core] = next;
|
||||
return next;
|
||||
}
|
||||
void signal(int64_t source, int64_t targetCore, unsigned reg,
|
||||
llvm::StringRef kind) {
|
||||
size_t begin = append(source, kind, 0, targetCore);
|
||||
signals[{targetCore, reg}].push_back({begin, source});
|
||||
append(source, "signal-complete", target.signalIssueNs);
|
||||
}
|
||||
void wait(int64_t core, unsigned reg, int64_t count, llvm::StringRef kind) {
|
||||
if (!count)
|
||||
return;
|
||||
size_t next = append(core, kind, 0, reg);
|
||||
if (!waits.try_emplace({core, reg}, Wait{next, count}).second)
|
||||
error = "multiple waits consume one event register in a generation";
|
||||
}
|
||||
void entrySynchronization();
|
||||
void completionSynchronization();
|
||||
bool boundary(const BoundaryProgram &program);
|
||||
bool transfer(const ScheduledTransferSlice &slice, bool send);
|
||||
bool connect();
|
||||
|
||||
std::vector<size_t> entry, tail;
|
||||
std::vector<bool> active;
|
||||
std::map<Register, std::vector<Signal>> signals;
|
||||
std::map<Register, Wait> waits;
|
||||
llvm::MapVector<int64_t, DirectEndpoint> sends, receives;
|
||||
};
|
||||
|
||||
void PeriodicPlan::entrySynchronization() {
|
||||
for (const ScheduledInfo &scheduled : transfers.scheduled)
|
||||
for (int64_t core : scheduled.cores) {
|
||||
auto found = transfers.hostReleaseSignals.find(core);
|
||||
if (found != transfers.hostReleaseSignals.end())
|
||||
for (HostReleaseSignal release : found->second)
|
||||
signal(core, release.writerCore, release.eventRegister, "free-signal");
|
||||
}
|
||||
unsigned rounds = 0;
|
||||
for (size_t distance = 1; distance < transfers.stageZeroCores.size(); distance *= 2)
|
||||
++rounds;
|
||||
unsigned last = transfers.synchronizationRegisterCount - 1;
|
||||
for (auto [rank, core] : llvm::enumerate(transfers.downstreamCores)) {
|
||||
int64_t parent = rank ? transfers.downstreamCores[(rank - 1) / 2]
|
||||
: transfers.stageZeroCores.front();
|
||||
signal(core, parent, rank ? last - 1 : last - rounds, "restart-permission");
|
||||
}
|
||||
}
|
||||
|
||||
void PeriodicPlan::completionSynchronization() {
|
||||
unsigned rounds = 0;
|
||||
for (size_t distance = 1; distance < transfers.stageZeroCores.size(); distance *= 2)
|
||||
++rounds;
|
||||
unsigned last = transfers.synchronizationRegisterCount - 1;
|
||||
for (auto [rank, core] : llvm::enumerate(transfers.stageZeroCores))
|
||||
for (unsigned round = 0; round < rounds; ++round) {
|
||||
int64_t peer = transfers.stageZeroCores[
|
||||
(rank + (size_t{1} << round)) % transfers.stageZeroCores.size()];
|
||||
signal(core, peer, last - round, "barrier-signal");
|
||||
wait(core, last - round, 1, "barrier-wait");
|
||||
}
|
||||
if (!transfers.downstreamCores.empty()) {
|
||||
int64_t leader = transfers.stageZeroCores.front();
|
||||
wait(leader, last - rounds, 1, "restart-permission-wait");
|
||||
signal(leader, transfers.downstreamCores.front(), last, "restart-signal");
|
||||
}
|
||||
for (auto [rank, core] : llvm::enumerate(transfers.downstreamCores)) {
|
||||
wait(core, last, 1, "restart-wait");
|
||||
size_t first = 2 * rank + 1;
|
||||
size_t end = std::min(first + 2, transfers.downstreamCores.size());
|
||||
if (first < end)
|
||||
wait(core, last - 1, end - first, "restart-permission-wait");
|
||||
for (size_t child = first; child < end; ++child)
|
||||
signal(core, transfers.downstreamCores[child], last, "restart-signal");
|
||||
}
|
||||
}
|
||||
|
||||
bool PeriodicPlan::transfer(const ScheduledTransferSlice &slice, bool send) {
|
||||
const ExternalTransferFamily &family = *slice.family;
|
||||
auto type = mlir::dyn_cast<mlir::RankedTensorType>(family.requirement->publicationFragmentType);
|
||||
if (!type || !type.hasStaticShape() || !type.getElementType().isIntOrFloat()) {
|
||||
error = "transfer payload has no static byte size";
|
||||
return false;
|
||||
}
|
||||
Cost bits = std::min<Cost>(type.getElementType().getIntOrFloatBitWidth(),
|
||||
target.computeBitwidth);
|
||||
Cost payloadBits = checkedMultiply(static_cast<Cost>(type.getNumElements()), bits);
|
||||
Cost bytes = payloadBits / 8 + (payloadBits % 8 != 0);
|
||||
for (size_t offset = 0; offset < slice.transferCount; ++offset) {
|
||||
size_t index = slice.familyOffset + offset;
|
||||
int64_t source = family.sourceCores.valueAt(index);
|
||||
int64_t destination = family.targetCores.valueAt(index);
|
||||
int64_t core = send ? source : destination;
|
||||
int64_t channel = family.channelIds.valueAt(index);
|
||||
if (!family.hostRouted) {
|
||||
size_t begin = append(core, send ? "send-begin" : "receive-begin", 0, channel);
|
||||
size_t end = append(core, send ? "send-complete" : "receive-complete", 0, channel);
|
||||
if (!(send ? sends : receives).insert({channel, {begin, end, core, bytes}}).second) {
|
||||
error = "direct channel has multiple physical endpoints";
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
unsigned reg = family.eventRegisters.valueAt(index);
|
||||
if (send) {
|
||||
if (family.hostStoreFlags.valueAt(index)) {
|
||||
SharedMemoryDemand demand = target.getSharedMemoryDemand(bytes, 1, true);
|
||||
boundaryMemory += demand;
|
||||
Cost service = checkedAdd(target.getLocalMemoryServiceNs(bytes, false),
|
||||
checkedAdd(target.getSharedMemoryLinkServiceNs(bytes, core, false), demand.serviceNs));
|
||||
append(core, "host-store", service, family.hostOffsets.valueAt(index));
|
||||
}
|
||||
signal(core, destination, reg, "ready-signal");
|
||||
} else {
|
||||
wait(core, reg, family.waitValues.valueAt(index), "ready-wait");
|
||||
SharedMemoryDemand demand = target.getSharedMemoryDemand(bytes, 1, false);
|
||||
boundaryMemory += demand;
|
||||
Cost service = checkedAdd(target.getSharedMemoryLinkServiceNs(
|
||||
target.controlMessageBytes, core, false),
|
||||
checkedAdd(demand.serviceNs, checkedAdd(
|
||||
target.getSharedMemoryLinkServiceNs(
|
||||
target.sharedMemoryReadReturnsPayload ? bytes : 0, core, true),
|
||||
target.getLocalMemoryServiceNs(bytes, true))));
|
||||
append(core, "host-load", service, family.hostOffsets.valueAt(index));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PeriodicPlan::boundary(const BoundaryProgram &program) {
|
||||
for (const BoundaryInstruction &instruction : program.instructions) {
|
||||
if (const auto *run = std::get_if<EmitSendRun>(&instruction)) {
|
||||
for (const auto &slice : run->slices)
|
||||
if (!transfer(slice, true))
|
||||
return false;
|
||||
} else if (const auto *run = std::get_if<EmitReceiveAssemblyRun>(&instruction)) {
|
||||
for (const auto &slice : run->slices)
|
||||
if (!transfer(slice, false))
|
||||
return false;
|
||||
} else if (const auto *reuse = std::get_if<EmitHostReuseWait>(&instruction)) {
|
||||
for (LaneInterval lanes : reuse->lanes.intervals())
|
||||
for (unsigned lane = lanes.begin; lane < lanes.end; ++lane)
|
||||
wait(program.key.first->cores[lane], reuse->eventRegisters.valueAt(lane),
|
||||
reuse->waitValues.valueAt(lane), "free-wait");
|
||||
}
|
||||
}
|
||||
return error.empty();
|
||||
}
|
||||
|
||||
bool PeriodicPlan::connect() {
|
||||
if (sends.size() != receives.size()) {
|
||||
error = "direct channel endpoint counts differ";
|
||||
return false;
|
||||
}
|
||||
for (const auto &[channel, send] : sends) {
|
||||
auto found = receives.find(channel);
|
||||
if (found == receives.end() || found->second.bytes != send.bytes) {
|
||||
error = "direct channel has no matching payload";
|
||||
return false;
|
||||
}
|
||||
const DirectEndpoint &receive = found->second;
|
||||
size_t permission = event(receive.core, "peer-permission", channel);
|
||||
edges.push_back({send.begin, permission,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, send.core, receive.core), 0});
|
||||
edges.push_back({receive.begin, permission, 0, 0});
|
||||
edges.push_back({permission, send.end, checkedAdd(
|
||||
target.getLinkServiceNs(target.controlMessageBytes, receive.core, send.core),
|
||||
target.getLocalMemoryServiceNs(send.bytes, false)), 0});
|
||||
edges.push_back({send.end, receive.end, checkedAdd(
|
||||
target.getLinkServiceNs(send.bytes, send.core, receive.core),
|
||||
target.getLocalMemoryServiceNs(send.bytes, true)), 0});
|
||||
}
|
||||
if (signals.size() != waits.size()) {
|
||||
error = "signal and wait register sets differ";
|
||||
return false;
|
||||
}
|
||||
for (const auto &[key, pending] : waits) {
|
||||
auto found = signals.find(key);
|
||||
if (found == signals.end() || pending.count < 0
|
||||
|| found->second.size() != static_cast<size_t>(pending.count)) {
|
||||
error = "event register does not receive its exact static count";
|
||||
return false;
|
||||
}
|
||||
for (Signal signal : found->second)
|
||||
edges.push_back({signal.event, pending.event,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, signal.core, key.first), 0});
|
||||
}
|
||||
for (size_t core = 0; core < active.size(); ++core)
|
||||
if (active[core])
|
||||
edges.push_back({tail[core], entry[core], 0, 1});
|
||||
return true;
|
||||
}
|
||||
|
||||
void PeriodicPlan::recordSynchronization(llvm::json::Object &report) const {
|
||||
llvm::json::Array registers;
|
||||
for (const auto &[key, pending] : waits) {
|
||||
llvm::json::Array sources;
|
||||
std::map<int64_t, int64_t> counts;
|
||||
auto found = signals.find(key);
|
||||
if (found != signals.end())
|
||||
for (Signal signal : found->second)
|
||||
++counts[signal.core];
|
||||
for (auto [core, count] : counts)
|
||||
sources.push_back(llvm::json::Object{{"core", core}, {"count", count}});
|
||||
registers.push_back(llvm::json::Object{{"core", key.first},
|
||||
{"register", key.second}, {"expected", pending.count},
|
||||
{"kind", events[pending.event].kind}, {"sources", std::move(sources)}});
|
||||
}
|
||||
report["event_registers"] = std::move(registers);
|
||||
}
|
||||
|
||||
bool PeriodicPlan::build(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredBoundaryPlan &boundaries) {
|
||||
if (!target.hasPeriodicTransferTiming()) {
|
||||
error = "target has no complete periodic communication timing contract";
|
||||
return false;
|
||||
}
|
||||
if (transfers.scheduled.empty() || transfers.stageZeroCores.empty()
|
||||
|| !transfers.synchronizationRegisterCount) {
|
||||
error = "periodic timing requires an active repeating pipeline body";
|
||||
return false;
|
||||
}
|
||||
for (auto [index, scheduled] : llvm::enumerate(transfers.scheduled)) {
|
||||
if (!materialization.materializedSchedules[index].runs.empty()
|
||||
&& scheduled.cores.size() != 1) {
|
||||
error = "compact compute runs require one physical core";
|
||||
return false;
|
||||
}
|
||||
for (int64_t core : scheduled.cores) {
|
||||
if (active[core]) {
|
||||
error = "physical core appears in multiple scheduled bodies";
|
||||
return false;
|
||||
}
|
||||
active[core] = true;
|
||||
tail[core] = entry[core] = event(core, "body-entry");
|
||||
}
|
||||
}
|
||||
entrySynchronization();
|
||||
llvm::DenseMap<std::pair<const ScheduledInfo *, unsigned>,
|
||||
const BoundaryProgram *> indexed;
|
||||
for (const BoundaryProgram &program : boundaries.boundaries)
|
||||
indexed[program.key] = &program;
|
||||
for (auto [recordIndex, record] : llvm::enumerate(materialization.materializedSchedules)) {
|
||||
const ScheduledInfo *scheduled = &transfers.scheduled[recordIndex];
|
||||
for (unsigned step = 0; step <= scheduled->stepCount; ++step) {
|
||||
if (const auto *program = indexed.lookup({scheduled, step}))
|
||||
if (!boundary(*program))
|
||||
return false;
|
||||
if (step == scheduled->stepCount)
|
||||
continue;
|
||||
auto appendCompute = [&](const ComputeInstance &instance, int64_t core) {
|
||||
auto found = graph.instanceToIndex.find(instance);
|
||||
if (found == graph.instanceToIndex.end()) {
|
||||
error = "scheduled compute instance is absent from the cost graph";
|
||||
return;
|
||||
}
|
||||
append(core, "compute", graph.nodes[found->second].cost, found->second);
|
||||
computeWork[core] = checkedAdd(computeWork[core], graph.nodes[found->second].cost);
|
||||
};
|
||||
if (!record.runs.empty()) {
|
||||
Cost cost = 0;
|
||||
for (const ComputeInstance &instance : record.runs[step].instances) {
|
||||
auto found = graph.instanceToIndex.find(instance);
|
||||
if (found == graph.instanceToIndex.end()) {
|
||||
error = "scheduled run instance is absent from the cost graph";
|
||||
return false;
|
||||
}
|
||||
cost = checkedAdd(cost, graph.nodes[found->second].cost);
|
||||
}
|
||||
append(scheduled->cores.front(), "compute-run", cost, step);
|
||||
int64_t core = scheduled->cores.front();
|
||||
computeWork[core] = checkedAdd(computeWork[core], cost);
|
||||
} else {
|
||||
for (auto [lane, instance] : llvm::enumerate(record.stepPlans[step].stepTuple.instances))
|
||||
appendCompute(instance, scheduled->cores[lane]);
|
||||
}
|
||||
}
|
||||
}
|
||||
completionSynchronization();
|
||||
return error.empty() && connect();
|
||||
}
|
||||
|
||||
static mlir::FailureOr<PeriodicDependencyEstimate> analyzePlan(PeriodicPlan &plan,
|
||||
const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredBoundaryPlan &boundaries) {
|
||||
if (!plan.build(graph, materialization, boundaries))
|
||||
return mlir::failure();
|
||||
return analyzePeriodicDependencies(plan.events.size(), plan.edges, plan.error);
|
||||
}
|
||||
|
||||
|
||||
} // namespace
|
||||
|
||||
llvm::json::Object getPeriodicScheduleReport(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredTransferPlan &transfers, const DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target) {
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
PeriodicPlan plan(target, transfers);
|
||||
llvm::json::Object report{{"diagnostic_only", true},
|
||||
{"selection_eligible", false},
|
||||
{"timing_model", "serial compute chunks; uncontended communication; no issue or local contention model"}};
|
||||
report["omitted_effects"] = llvm::json::Array{
|
||||
"placement and timing of baseline memory accesses",
|
||||
"communication introduced after deferred realization, including final output collection",
|
||||
"instruction issue, execution-unit overlap and local-memory contention",
|
||||
"projection materialization, strided transfer splitting and load folding",
|
||||
"network injection queues and global-memory arbitration"};
|
||||
report["native_host_buffer_bytes"] = static_cast<int64_t>(transfers.pipelineHostBufferBytes);
|
||||
auto estimate = analyzePlan(plan, graph, materialization, boundaries);
|
||||
if (mlir::succeeded(estimate)) {
|
||||
plan.recordSynchronization(report);
|
||||
SharedMemoryDemand memory = graph.baselineMemory;
|
||||
memory += plan.boundaryMemory;
|
||||
report["recurrence_lower_ns"] = estimate->recurrenceLowerNs;
|
||||
report["recurrence_upper_ns"] = estimate->recurrenceUpperNs;
|
||||
report["within_generation_span_ns"] = static_cast<int64_t>(estimate->withinGenerationSpanNs);
|
||||
report["global_memory_service_ns"] = static_cast<int64_t>(memory.serviceNs);
|
||||
report["baseline_memory_service_ns"] = static_cast<int64_t>(graph.baselineMemory.serviceNs);
|
||||
report["boundary_memory_service_ns"] = static_cast<int64_t>(plan.boundaryMemory.serviceNs);
|
||||
report["boundary_read_bytes"] = static_cast<int64_t>(plan.boundaryMemory.readBytes);
|
||||
report["boundary_write_bytes"] = static_cast<int64_t>(plan.boundaryMemory.writeBytes);
|
||||
report["boundary_read_requests"] = static_cast<int64_t>(plan.boundaryMemory.readRequests);
|
||||
report["boundary_write_requests"] = static_cast<int64_t>(plan.boundaryMemory.writeRequests);
|
||||
Cost coreWork = *std::max_element(plan.computeWork.begin(), plan.computeWork.end());
|
||||
report["maximum_core_compute_ns"] = static_cast<int64_t>(coreWork);
|
||||
report["interval_estimate_ns"] = std::max({estimate->recurrenceUpperNs,
|
||||
static_cast<double>(memory.serviceNs), static_cast<double>(coreWork)});
|
||||
report["relaxation_rounds"] = static_cast<int64_t>(estimate->relaxationRounds);
|
||||
llvm::json::Array cycle;
|
||||
std::map<llvm::StringRef, int64_t> kinds;
|
||||
std::map<int64_t, Cost> coreDelays;
|
||||
std::map<std::pair<int64_t, int64_t>, Cost> linkDelays;
|
||||
Cost delay = 0, distance = 0;
|
||||
for (size_t index : estimate->criticalCycle) {
|
||||
const auto &edge = plan.edges[index];
|
||||
const Event &source = plan.events[edge.source], &destination = plan.events[edge.target];
|
||||
delay = checkedAdd(delay, edge.delayNs);
|
||||
distance = checkedAdd(distance, static_cast<Cost>(edge.distance));
|
||||
++kinds[destination.kind];
|
||||
coreDelays[destination.core] = checkedAdd(coreDelays[destination.core], edge.delayNs);
|
||||
if (source.core != destination.core)
|
||||
linkDelays[{source.core, destination.core}] = checkedAdd(
|
||||
linkDelays[{source.core, destination.core}], edge.delayNs);
|
||||
if (cycle.size() < 128)
|
||||
cycle.push_back(llvm::json::Object{{"source_core", source.core},
|
||||
{"source_kind", source.kind}, {"target_core", destination.core},
|
||||
{"target_kind", destination.kind}, {"identity", destination.identity},
|
||||
{"delay_ns", static_cast<int64_t>(edge.delayNs)},
|
||||
{"distance", edge.distance}});
|
||||
}
|
||||
llvm::json::Object counts;
|
||||
for (auto [kind, count] : kinds)
|
||||
counts[kind] = count;
|
||||
report["critical_cycle"] = std::move(cycle);
|
||||
report["critical_cycle_event_counts"] = std::move(counts);
|
||||
report["critical_cycle_edges"] = static_cast<int64_t>(estimate->criticalCycle.size());
|
||||
report["critical_cycle_delay_ns"] = static_cast<int64_t>(delay);
|
||||
report["critical_cycle_distance"] = static_cast<int64_t>(distance);
|
||||
llvm::json::Array cores, links;
|
||||
for (auto [core, ns] : coreDelays)
|
||||
cores.push_back(llvm::json::Object{{"core", core}, {"delay_ns", static_cast<int64_t>(ns)}});
|
||||
for (auto [pair, ns] : linkDelays)
|
||||
links.push_back(llvm::json::Object{{"source", pair.first}, {"target", pair.second},
|
||||
{"delay_ns", static_cast<int64_t>(ns)}});
|
||||
report["critical_cycle_cores"] = std::move(cores);
|
||||
report["critical_cycle_links"] = std::move(links);
|
||||
}
|
||||
report["status"] = plan.error.empty() ? "estimated" : "unavailable";
|
||||
if (!plan.error.empty())
|
||||
report["reason"] = plan.error;
|
||||
report["events"] = static_cast<int64_t>(plan.events.size());
|
||||
report["edges"] = static_cast<int64_t>(plan.edges.size());
|
||||
llvm::json::Object eventCounts;
|
||||
std::map<llvm::StringRef, int64_t> counts;
|
||||
for (const Event &event : plan.events)
|
||||
++counts[event.kind];
|
||||
for (auto [kind, count] : counts)
|
||||
eventCounts[kind] = count;
|
||||
report["event_counts"] = std::move(eventCounts);
|
||||
report["analysis_wall_ms"] = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
return report;
|
||||
}
|
||||
|
||||
void dumpPeriodicScheduleEstimate(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredTransferPlan &transfers, const DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target) {
|
||||
auto file = openDialectDumpFileWithExtension("pipeline_periodic", "/reports", "json");
|
||||
if (!file.is_open())
|
||||
return;
|
||||
auto report = getPeriodicScheduleReport(graph, materialization, transfers,
|
||||
boundaries, target);
|
||||
llvm::raw_os_ostream os(file);
|
||||
os << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(report)));
|
||||
}
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredBoundaryPlanning.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ComputeGraph.hpp"
|
||||
#include "llvm/Support/JSON.h"
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace spatial { struct ScheduledComputeMaterializationResult; }
|
||||
struct PimInstructionTiming;
|
||||
|
||||
llvm::json::Object getPeriodicScheduleReport(const spatial::ComputeGraph &graph,
|
||||
const spatial::ScheduledComputeMaterializationResult &materialization,
|
||||
const spatial::DeferredTransferPlan &transfers, const spatial::DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target);
|
||||
|
||||
// Read-only diagnostics over the final physical transfer and synchronization plan.
|
||||
void dumpPeriodicScheduleEstimate(const spatial::ComputeGraph &graph,
|
||||
const spatial::ScheduledComputeMaterializationResult &materialization,
|
||||
const spatial::DeferredTransferPlan &transfers, const spatial::DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,663 +0,0 @@
|
||||
#include "PimSpatialCost.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "PimTimingArithmetic.hpp"
|
||||
#include "PimBinaryFormat.hpp"
|
||||
#include "PimCompilerUtils.hpp"
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "PimScheduleDiagnostic.hpp"
|
||||
#include "src/Accelerators/PIM/Common/IR/ConstantUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Common/IR/CopyAccessPlan.hpp"
|
||||
#include "src/Accelerators/PIM/Common/IR/ShapeUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Common/IR/ShapingUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Conversion/SpatialToPim/ComputeLikeRegionUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredProjectionAnalysis.hpp"
|
||||
#include "mlir/Dialect/Linalg/IR/Linalg.h"
|
||||
#include "mlir/Dialect/Func/IR/FuncOps.h"
|
||||
#include "mlir/Dialect/SCF/IR/SCF.h"
|
||||
#include "mlir/IR/Matchers.h"
|
||||
#include "llvm/ADT/SmallPtrSet.h"
|
||||
#include "llvm/ADT/DenseSet.h"
|
||||
#include "llvm/Support/MathExtras.h"
|
||||
#include <chrono>
|
||||
#include <array>
|
||||
#include <map>
|
||||
#include <limits>
|
||||
|
||||
using namespace mlir;
|
||||
using namespace onnx_mlir;
|
||||
using namespace onnx_mlir::spatial;
|
||||
using pim_timing::add;
|
||||
using pim_timing::mul;
|
||||
using pim_timing::ceil;
|
||||
namespace {
|
||||
using Event = PimExecutionEvent;
|
||||
using Sequence = std::vector<Event>;
|
||||
enum class Residence { Local, Host, Constant, Zero, CapturedWeight };
|
||||
|
||||
PimPeriodicEstimate unavailableCost(llvm::StringRef reason) {
|
||||
PimPeriodicEstimate result;
|
||||
result.cost.reason = reason.str();
|
||||
result.report = llvm::json::Object{{"status", "unavailable"}, {"cost_available", false},
|
||||
{"convergence_proved", nullptr}, {"lowering_supported", nullptr},
|
||||
{"safe_for_selection", false}, {"reason", reason.str()}};
|
||||
return result;
|
||||
}
|
||||
|
||||
class Extraction {
|
||||
public:
|
||||
const PimInstructionTiming ⌖
|
||||
bool diagnostics;
|
||||
bool omitSynchronization;
|
||||
PimExecutionProgram program;
|
||||
std::string error, loweringReason;
|
||||
StaticLoweringSupport loweringSupport = StaticLoweringSupport::Supported;
|
||||
std::map<std::string, int64_t> gaps;
|
||||
int64_t visited = 0, constantLoads = 0;
|
||||
explicit Extraction(const PimInstructionTiming &target, bool diagnostics, bool omitSynchronization)
|
||||
: target(target), diagnostics(diagnostics), omitSynchronization(omitSynchronization),
|
||||
program(target.processorCount) {}
|
||||
bool build(ModuleOp module);
|
||||
private:
|
||||
// Bound interpretation per physical core, independently of batch lane count.
|
||||
static constexpr size_t maximumCoreVisits = 1000000;
|
||||
size_t coreVisits = 0;
|
||||
int64_t currentCore = -1;
|
||||
llvm::SmallDenseSet<int64_t, 16> assignedCores;
|
||||
DenseMap<Value, Residence> residence;
|
||||
DenseMap<Value, CopyAccessPlan> publicationAccess;
|
||||
DenseMap<Value, SmallVector<unsigned, 2>> directOutputs;
|
||||
llvm::SmallDenseSet<Value, 4> compactStorage;
|
||||
llvm::SmallPtrSet<Operation *, 32> indexed;
|
||||
StaticIndexEnvironment environment;
|
||||
Residence storage(Value value);
|
||||
uint64_t elements(Type type) {
|
||||
auto shape = dyn_cast<ShapedType>(type);
|
||||
if (!shape || !shape.hasStaticShape()) {
|
||||
error = "abstract work requires a static shaped payload";
|
||||
return 0;
|
||||
}
|
||||
if (!shape.getElementType().isIntOrFloat() || shape.getElementTypeBitWidth() != 32) {
|
||||
error = "abstract precision projection requires 32-bit elements";
|
||||
return 0;
|
||||
}
|
||||
uint64_t result = 1;
|
||||
for (int64_t dimension : shape.getShape()) result = mul(result, dimension);
|
||||
return result;
|
||||
}
|
||||
uint64_t bytes(Type type) {
|
||||
uint64_t count = elements(type);
|
||||
auto shaped = dyn_cast<ShapedType>(type);
|
||||
if (!shaped || !shaped.getElementType().isIntOrFloat()) {
|
||||
error = "abstract transfer requires a scalar integer or floating element";
|
||||
return 0;
|
||||
}
|
||||
uint64_t nativeBytes = ceil(mul(count, shaped.getElementTypeBitWidth()), 8);
|
||||
if (nativeBytes > std::numeric_limits<int32_t>::max()) {
|
||||
loweringSupport = StaticLoweringSupport::Unknown;
|
||||
loweringReason = "native transfer size requires backend normalization and size verification";
|
||||
}
|
||||
return ceil(mul(count, target.computeBitwidth), 8);
|
||||
}
|
||||
void work(Sequence &sequence, uint64_t ns, Event::WorkClass resource = Event::LocalCopy) {
|
||||
if (!ns) return;
|
||||
if (!sequence.empty() && sequence.back().kind == Event::Work
|
||||
&& sequence.back().workClass == resource)
|
||||
sequence.back().amount = add(sequence.back().amount, ns);
|
||||
else {
|
||||
sequence.push_back({Event::Work, ns});
|
||||
sequence.back().workClass = resource;
|
||||
}
|
||||
}
|
||||
uint64_t localWork(uint64_t bytes, bool read, bool write) const {
|
||||
return getPimLocalTransferWorkNs(target, bytes, read, write);
|
||||
}
|
||||
void materialize(Value value, Sequence &sequence);
|
||||
bool accessSlice(tensor::ExtractSliceOp slice, Sequence &sequence, bool host);
|
||||
bool block(Block &body, Sequence &sequence);
|
||||
bool operation(Operation &op, Sequence &sequence);
|
||||
bool loop(scf::ForOp op, Sequence &sequence);
|
||||
bool core(Operation *op, int64_t physicalCore, unsigned lane);
|
||||
};
|
||||
|
||||
Residence Extraction::storage(Value value) {
|
||||
if (auto it = residence.find(value); it != residence.end()) return it->second;
|
||||
Attribute constant;
|
||||
if (matchPattern(value, m_Constant(&constant)))
|
||||
return isZeroBitPatternSplat(constant) ? Residence::Zero : Residence::Constant;
|
||||
if (auto slice = value.getDefiningOp<tensor::ExtractSliceOp>()) return storage(slice.getSource());
|
||||
if (auto collapse = value.getDefiningOp<tensor::CollapseShapeOp>()) return storage(collapse.getSrc());
|
||||
if (auto expand = value.getDefiningOp<tensor::ExpandShapeOp>()) return storage(expand.getSrc());
|
||||
if (auto cast = value.getDefiningOp<tensor::CastOp>()) return storage(cast.getSource());
|
||||
if (auto branch = value.getDefiningOp<scf::IfOp>()) {
|
||||
auto condition = evaluateDeferredIndex(branch.getCondition(), environment);
|
||||
if (succeeded(condition)) {
|
||||
Region ®ion = *condition ? branch.getThenRegion() : branch.getElseRegion();
|
||||
return storage(region.front().getTerminator()->getOperand(cast<OpResult>(value).getResultNumber()));
|
||||
}
|
||||
}
|
||||
if (auto arg = dyn_cast<BlockArgument>(value)) {
|
||||
if (auto loop = dyn_cast_or_null<scf::ForOp>(arg.getOwner()->getParentOp()))
|
||||
if (arg.getArgNumber()) return Residence::Local;
|
||||
return Residence::Host;
|
||||
}
|
||||
if (isa_and_nonnull<SpatVMMOp, SpatVAddOp, SpatVSubOp, SpatVMulOp,
|
||||
SpatVMaxOp, SpatVVDMulOp, SpatVAvgOp, SpatReluOp, SpatSigmoidOp, SpatSoftmaxOp,
|
||||
SpatChannelReceiveOp, SpatHostWaitLoadOp, SpatScheduledCompute,
|
||||
SpatScheduledComputeBatch, SpatConcatOp, tensor::EmptyOp,
|
||||
tensor::InsertSliceOp, tensor::PadOp, linalg::TransposeOp, scf::ForOp>(value.getDefiningOp()))
|
||||
return Residence::Local;
|
||||
error = "abstract storage residence is unavailable for "
|
||||
+ value.getDefiningOp()->getName().getStringRef().str();
|
||||
return Residence::Local; // The caller discards the estimate when error is set.
|
||||
}
|
||||
|
||||
void Extraction::materialize(Value value, Sequence &sequence) {
|
||||
auto place = storage(value);
|
||||
if (place == Residence::Host || place == Residence::Constant || place == Residence::CapturedWeight) {
|
||||
sequence.push_back({Event::Load, bytes(value.getType())});
|
||||
// Captured weights remain block arguments; only direct global zero loads fold to fills.
|
||||
if (place == Residence::Constant || place == Residence::CapturedWeight) {
|
||||
++constantLoads;
|
||||
sequence.back().constant = true;
|
||||
}
|
||||
} else if (place == Residence::Zero) {
|
||||
work(sequence, localWork(bytes(value.getType()), false, true), Event::Fill);
|
||||
}
|
||||
}
|
||||
|
||||
bool Extraction::accessSlice(tensor::ExtractSliceOp slice, Sequence &sequence, bool host) {
|
||||
auto source = computeRowMajorStridesChecked(slice.getSourceType().getShape());
|
||||
auto destination = computeRowMajorStridesChecked(slice.getStaticSizes());
|
||||
if (failed(source) || failed(destination)) { error = "abstract slice geometry unavailable"; return false; }
|
||||
SmallVector<int64_t> strides;
|
||||
for (auto [stride, scale] : llvm::zip(*source, slice.getStaticStrides())) {
|
||||
int64_t result;
|
||||
if (scale <= 0 || llvm::MulOverflow(stride, scale, result)) {
|
||||
error = "abstract slice stride unavailable"; return false;
|
||||
}
|
||||
strides.push_back(result);
|
||||
}
|
||||
auto copy = CopyAccessPlan::build(slice.getStaticSizes(), strides, *destination);
|
||||
if (failed(copy)) { error = "abstract slice access plan unavailable"; return false; }
|
||||
uint64_t size = ceil(mul(copy->getRunElements(), target.computeBitwidth), 8);
|
||||
if (host) {
|
||||
sequence.push_back({Event::Repeat, static_cast<uint64_t>(copy->getRunCount()),
|
||||
0, 0, 0, {{Event::Load, size}}});
|
||||
residence[slice.getResult()] = Residence::Local;
|
||||
compactStorage.insert(slice.getResult());
|
||||
} else if (compactStorage.contains(slice.getSource())
|
||||
&& slice.getSourceType().getRank() == slice.getType().getRank()
|
||||
&& llvm::all_of(slice.getResult().getUsers(), [](Operation *user) {
|
||||
return isa<SpatHostStoreSyncOp>(user);
|
||||
})) {
|
||||
// Publication-only slices retain the compact source's subview geometry.
|
||||
publicationAccess.insert_or_assign(slice.getResult(), *copy);
|
||||
} else if (copy->getRunCount() > 1) {
|
||||
if (diagnostics) ++gaps["local slice materialization and forwarding"];
|
||||
work(sequence, mul(copy->getRunCount(), localWork(size, true, true)));
|
||||
}
|
||||
if (compactStorage.contains(slice.getSource()) && copy->getRunCount() == 1)
|
||||
compactStorage.insert(slice.getResult());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Extraction::loop(scf::ForOp op, Sequence &sequence) {
|
||||
auto lower = evaluateDeferredIndex(op.getLowerBound(), environment);
|
||||
auto upper = evaluateDeferredIndex(op.getUpperBound(), environment);
|
||||
auto step = evaluateDeferredIndex(op.getStep(), environment);
|
||||
if (failed(lower) || failed(upper) || failed(step) || *step <= 0) {
|
||||
error = "abstract loop has unavailable static bounds"; return false;
|
||||
}
|
||||
for (Value initial : op.getInitArgs()) materialize(initial, sequence);
|
||||
int64_t distance = 0;
|
||||
if (*upper > *lower && llvm::SubOverflow(*upper, *lower, distance)) {
|
||||
error = "unrepresentable abstract loop trip count"; return false;
|
||||
}
|
||||
uint64_t count = ceil(distance, *step);
|
||||
bool indexSensitive = indexed.contains(op);
|
||||
if (indexSensitive && count > 100000) {
|
||||
error = "abstract indexed loop exceeds analysis budget"; return false;
|
||||
}
|
||||
if (!count) return true;
|
||||
if (indexSensitive) {
|
||||
for (uint64_t i = 0; i < count; ++i) {
|
||||
int64_t induction;
|
||||
if (llvm::AddOverflow(*lower, static_cast<int64_t>(mul(i, *step)), induction)) {
|
||||
error = "unrepresentable abstract induction value"; return false;
|
||||
}
|
||||
environment.bindings[op.getInductionVar()] = induction;
|
||||
if (!block(*op.getBody(), sequence)) return false;
|
||||
}
|
||||
} else {
|
||||
environment.bindings[op.getInductionVar()] = *lower;
|
||||
Event repeat{Event::Repeat, count};
|
||||
if (!block(*op.getBody(), repeat.body)) return false;
|
||||
sequence.push_back(std::move(repeat));
|
||||
}
|
||||
environment.bindings.erase(op.getInductionVar());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Extraction::operation(Operation &op, Sequence &sequence) {
|
||||
if (auto loopOp = dyn_cast<scf::ForOp>(op)) return loop(loopOp, sequence);
|
||||
if (auto branch = dyn_cast<scf::IfOp>(op)) {
|
||||
auto condition = evaluateDeferredIndex(branch.getCondition(), environment);
|
||||
if (failed(condition)) { error = "abstract branch condition is unavailable"; return false; }
|
||||
Region ®ion = *condition ? branch.getThenRegion() : branch.getElseRegion();
|
||||
return region.empty() || block(region.front(), sequence);
|
||||
}
|
||||
auto index = [&](Value value) -> int64_t {
|
||||
auto result = evaluateDeferredIndex(value, environment);
|
||||
if (failed(result)) { error = "abstract communication index is unavailable"; return -1; }
|
||||
return *result;
|
||||
};
|
||||
if (auto sync = dyn_cast<SpatSyncOp>(op)) {
|
||||
if (!omitSynchronization)
|
||||
sequence.push_back({Event::Signal, 0, index(sync.getTargetCoreId()), index(sync.getEventRegister())});
|
||||
} else if (auto wait = dyn_cast<SpatWaitOp>(op)) {
|
||||
if (!omitSynchronization) {
|
||||
int64_t count = index(wait.getWaitValue());
|
||||
if (count) sequence.push_back({Event::Wait, 0, 0, index(wait.getEventRegister()), count});
|
||||
}
|
||||
} else if (auto send = dyn_cast<SpatChannelSendOp>(op)) {
|
||||
materialize(send.getInput(), sequence);
|
||||
sequence.push_back({Event::Send, bytes(send.getInput().getType()), index(send.getTargetCoreId())});
|
||||
} else if (auto recv = dyn_cast<SpatChannelReceiveOp>(op)) {
|
||||
sequence.push_back({Event::Receive, bytes(recv.getOutput().getType()), index(recv.getSourceCoreId())});
|
||||
} else if (auto store = dyn_cast<SpatHostStoreSyncOp>(op)) {
|
||||
materialize(store.getInput(), sequence);
|
||||
if (auto plan = publicationAccess.find(store.getInput()); plan != publicationAccess.end())
|
||||
sequence.push_back({Event::Repeat, static_cast<uint64_t>(plan->second.getRunCount()),
|
||||
0, 0, 0, {{Event::Store, ceil(mul(plan->second.getRunElements(), target.computeBitwidth), 8)}}});
|
||||
else sequence.push_back({Event::Store, bytes(store.getInput().getType())});
|
||||
if (!omitSynchronization)
|
||||
sequence.push_back({Event::Signal, 0, index(store.getTargetCoreId()), index(store.getEventRegister())});
|
||||
} else if (auto load = dyn_cast<SpatHostWaitLoadOp>(op)) {
|
||||
if (!omitSynchronization) {
|
||||
int64_t count = index(load.getWaitValue());
|
||||
if (count) sequence.push_back({Event::Wait, 0, 0, index(load.getEventRegister()), count});
|
||||
}
|
||||
sequence.push_back({Event::Load, bytes(load.getOutput().getType())});
|
||||
} else if (auto vmm = dyn_cast<SpatVMMOp>(op)) {
|
||||
materialize(vmm.getInput(), sequence);
|
||||
auto weight = dyn_cast<RankedTensorType>(vmm.getWeight().getType());
|
||||
if (!weight || weight.getRank() != 2 || !weight.hasStaticShape() || !target.matrixColumns
|
||||
|| weight.getDimSize(1) <= 0
|
||||
|| static_cast<uint64_t>(weight.getDimSize(1)) % target.matrixColumns
|
||||
|| weight.getDimSize(0) <= 0
|
||||
|| static_cast<uint64_t>(weight.getDimSize(0)) > target.matrixRows
|
||||
|| weight.getEncoding() || !weight.getElementType().isIntOrFloat()
|
||||
|| weight.getElementTypeBitWidth() != 32) {
|
||||
error = "unavailable physical matrix weight geometry"; return false;
|
||||
}
|
||||
if (diagnostics && static_cast<uint64_t>(weight.getDimSize(0)) < target.matrixRows)
|
||||
++gaps["matrix input padding and copy forwarding"];
|
||||
uint64_t output = getPimMatrixOutputBytes(target, target.matrixCellBits,
|
||||
pim_binary::kMatrixWeightPrecisionBits, weight.getDimSize(1) / target.matrixColumns,
|
||||
ceil(target.computeBitwidth, 8));
|
||||
work(sequence, getPimMatrixWorkNs(target, target.computeBitwidth, output), Event::Matrix);
|
||||
} else if (auto softmax = dyn_cast<SpatSoftmaxOp>(op)) {
|
||||
materialize(softmax.getInput(), sequence);
|
||||
// Pimsim-nn omits vsoftmax itself. Keep any preceding input materialization.
|
||||
} else if (isa<SpatVAddOp, SpatVSubOp, SpatVMulOp, SpatVMaxOp,
|
||||
SpatVVDMulOp, SpatVAvgOp, SpatReluOp, SpatSigmoidOp>(op)) {
|
||||
for (Value operand : op.getOperands()) materialize(operand, sequence);
|
||||
uint64_t width = ceil(target.computeBitwidth, 8);
|
||||
work(sequence, getPimVectorWorkNs(target, elements(op.getOperand(0).getType()),
|
||||
width, width, op.getNumOperands() == 2), Event::Vector);
|
||||
} else if (auto extract = dyn_cast<tensor::ExtractSliceOp>(op)) {
|
||||
auto place = storage(extract.getSource());
|
||||
if (place == Residence::Host || place == Residence::Local)
|
||||
if (!accessSlice(extract, sequence, place == Residence::Host)) return false;
|
||||
} else if (auto insert = dyn_cast<tensor::InsertSliceOp>(op)) {
|
||||
materialize(insert.getSource(), sequence);
|
||||
uint64_t size = bytes(insert.getSource().getType());
|
||||
work(sequence, localWork(size, true, true));
|
||||
if (compactStorage.contains(insert.getDest())) compactStorage.insert(insert.getResult());
|
||||
if (diagnostics) ++gaps["output copy forwarding"];
|
||||
} else if (auto transpose = dyn_cast<linalg::TransposeOp>(op)) {
|
||||
materialize(transpose.getInput(), sequence);
|
||||
auto type = cast<ShapedType>(transpose.getInput().getType());
|
||||
uint64_t volume = elements(type);
|
||||
if (!volume) {
|
||||
if (error.empty()) error = "zero-element transpose has no abstract timing contract";
|
||||
return false;
|
||||
}
|
||||
if (failed(computeRowMajorStridesChecked(type.getShape()))) {
|
||||
error = "abstract transpose geometry unavailable"; return false;
|
||||
}
|
||||
auto run = getTransposeRun(type.getShape(), transpose.getPermutation());
|
||||
uint64_t width = ceil(target.computeBitwidth, 8);
|
||||
uint64_t runBytes = mul(run.elements, width);
|
||||
uint64_t cost = run.sourceStride == 1
|
||||
? localWork(runBytes, true, true)
|
||||
: getPimVectorWorkNs(target, run.elements, width, width, false);
|
||||
work(sequence, mul(volume / run.elements, cost),
|
||||
run.sourceStride == 1 ? Event::LocalCopy : Event::VectorCopy);
|
||||
if (diagnostics) ++gaps["transpose alias and constant folding"];
|
||||
} else if (auto pad = dyn_cast<tensor::PadOp>(op)) {
|
||||
materialize(pad.getSource(), sequence);
|
||||
work(sequence, localWork(bytes(pad.getResult().getType()), false, true), Event::Fill);
|
||||
work(sequence, localWork(bytes(pad.getSource().getType()), true, true));
|
||||
if (diagnostics) ++gaps["padding fill and copy normalization"];
|
||||
} else if (auto concat = dyn_cast<SpatConcatOp>(op)) {
|
||||
for (Value input : concat.getInputs()) {
|
||||
materialize(input, sequence);
|
||||
uint64_t size = bytes(input.getType());
|
||||
work(sequence, localWork(size, true, true));
|
||||
}
|
||||
compactStorage.insert(concat.getOutput());
|
||||
if (diagnostics) ++gaps["concat alias and copy elimination"];
|
||||
} else if (auto empty = dyn_cast<tensor::EmptyOp>(op)) {
|
||||
compactStorage.insert(empty.getResult());
|
||||
} else if (isa<arith::ConstantOp, tensor::ExtractOp,
|
||||
tensor::CollapseShapeOp, tensor::ExpandShapeOp, tensor::CastOp,
|
||||
scf::YieldOp, SpatYieldOp>(op) || isPureIndexComputationOp(&op)) {
|
||||
// Compile-time shape/index work has no device execution cost.
|
||||
} else if (auto parallel = dyn_cast<SpatInParallelOp>(op)) {
|
||||
auto batch = parallel->getParentOfType<SpatScheduledComputeBatch>();
|
||||
auto first = batch ? batch.getOutputArgument(0) : std::nullopt;
|
||||
if (!first) { error = "unavailable abstract batch output mapping"; return false; }
|
||||
for (Operation &nested : parallel.getRegion().front()) {
|
||||
auto insert = dyn_cast<tensor::ParallelInsertSliceOp>(nested);
|
||||
auto destination = insert ? dyn_cast<BlockArgument>(insert.getDest()) : BlockArgument{};
|
||||
if (!destination || destination.getArgNumber() < first->getArgNumber()) {
|
||||
error = "unsupported abstract batch output"; return false;
|
||||
}
|
||||
unsigned result = destination.getArgNumber() - first->getArgNumber();
|
||||
if (result >= batch.getNumResults()) { error = "invalid abstract batch output"; return false; }
|
||||
if (succeeded(getDirectReturnOperandIndex(cast<OpResult>(batch.getResult(result))))) {
|
||||
materialize(insert.getSource(), sequence);
|
||||
sequence.push_back({Event::Store, bytes(insert.getSource().getType())});
|
||||
} else if (!batch.getResult(result).use_empty()) {
|
||||
error = "unavailable indirect batch output collection"; return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
error = "unsupported abstract operation: " + op.getName().getStringRef().str();
|
||||
return false;
|
||||
}
|
||||
return error.empty();
|
||||
}
|
||||
|
||||
bool Extraction::block(Block &body, Sequence &sequence) {
|
||||
for (Operation &op : body) {
|
||||
++visited;
|
||||
if (++coreVisits > maximumCoreVisits) {
|
||||
error = "abstract extraction budget exceeded on physical core "
|
||||
+ std::to_string(currentCore);
|
||||
return false;
|
||||
}
|
||||
if (!operation(op, sequence)) return false;
|
||||
for (Value result : op.getResults())
|
||||
if (auto outputs = directOutputs.find(result); outputs != directOutputs.end())
|
||||
// Lowering inserts each store immediately after the shared producer.
|
||||
for (unsigned destination : llvm::reverse(outputs->second)) {
|
||||
(void)destination; // Distinct host destinations require distinct stores.
|
||||
sequence.push_back({Event::Store, bytes(result.getType())});
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Extraction::core(Operation *op, int64_t physicalCore, unsigned lane) {
|
||||
if (physicalCore < 0 || physicalCore >= static_cast<int64_t>(program.size())) {
|
||||
loweringSupport = StaticLoweringSupport::Unsupported;
|
||||
error = "physical core ID is outside the target: " + std::to_string(physicalCore); return false;
|
||||
}
|
||||
if (!assignedCores.insert(physicalCore).second) {
|
||||
loweringSupport = StaticLoweringSupport::Unsupported;
|
||||
error = "duplicate physical core assignment: " + std::to_string(physicalCore); return false;
|
||||
}
|
||||
coreVisits = 0; currentCore = physicalCore;
|
||||
residence.clear(); publicationAccess.clear(); directOutputs.clear(); compactStorage.clear();
|
||||
environment.bindings.clear();
|
||||
ValueRange inputs, weights;
|
||||
auto single = dyn_cast<SpatScheduledCompute>(op);
|
||||
auto batch = dyn_cast<SpatScheduledComputeBatch>(op);
|
||||
if (single) { inputs = single.getInputs(); weights = single.getWeights(); }
|
||||
else { inputs = batch.getInputs(); weights = batch.getWeights(); environment.bindings[*batch.getLaneArgument()] = lane; }
|
||||
Sequence &sequence = program[physicalCore];
|
||||
if (single) {
|
||||
auto yield = cast<SpatYieldOp>(single.getBody().front().getTerminator());
|
||||
for (auto [result, value] : llvm::zip(single.getResults(), yield.getOperands()))
|
||||
if (auto destination = getDirectReturnOperandIndex(cast<OpResult>(result)); succeeded(destination)) {
|
||||
if (!value.getDefiningOp() || value.getDefiningOp()->getBlock() != &single.getBody().front()) {
|
||||
error = "unavailable direct output insertion position"; return false;
|
||||
}
|
||||
directOutputs[value].push_back(*destination);
|
||||
} else if (!result.use_empty()) {
|
||||
error = "unavailable indirect compute output collection"; return false;
|
||||
}
|
||||
}
|
||||
for (unsigned i = 0; i < weights.size(); ++i)
|
||||
residence[single ? *single.getWeightArgument(i) : *batch.getWeightArgument(i)] = Residence::CapturedWeight;
|
||||
for (unsigned i = 0; i < inputs.size(); ++i) {
|
||||
Value argument = single ? *single.getInputArgument(i) : *batch.getInputArgument(i);
|
||||
auto plan = planComputeInputMaterialization(op, i);
|
||||
if (failed(plan)) { error = "input materialization plan unavailable"; return false; }
|
||||
residence[argument] = storage(inputs[i]);
|
||||
// FuncOpArgToGlobalMemoryPattern removes this input and exposes the host
|
||||
// tensor in the body before entry-copy materialization runs.
|
||||
if (*plan == ComputeInputMaterialization::ForwardFunctionInput) {
|
||||
if (diagnostics) ++gaps["function-input whole-load versus slice materialization"];
|
||||
continue;
|
||||
}
|
||||
if (*plan == ComputeInputMaterialization::CopyAtEntry) {
|
||||
materialize(inputs[i], sequence);
|
||||
residence[argument] = Residence::Local;
|
||||
compactStorage.insert(argument);
|
||||
if (diagnostics) ++gaps["input host slicing and receive sinking"];
|
||||
}
|
||||
}
|
||||
return block(op->getRegion(0).front(), sequence);
|
||||
}
|
||||
|
||||
bool Extraction::build(ModuleOp module) {
|
||||
bool okay = true;
|
||||
module.walk<WalkOrder::PostOrder>([&](Operation *op) {
|
||||
if (indexed.contains(op) || isa<SpatChannelSendOp, SpatChannelReceiveOp,
|
||||
SpatSyncOp, SpatWaitOp, SpatHostStoreSyncOp, SpatHostWaitLoadOp, scf::IfOp>(op))
|
||||
if (Operation *parent = op->getParentOp()) indexed.insert(parent);
|
||||
});
|
||||
module.walk([&](Operation *op) {
|
||||
if (!okay) return WalkResult::interrupt();
|
||||
if (auto single = dyn_cast<SpatScheduledCompute>(op)) {
|
||||
auto coreId = op->getAttrOfType<IntegerAttr>("coreId");
|
||||
if (!coreId) { error = "missing physical core"; okay = false; }
|
||||
else okay = core(op, coreId.getInt(), 0);
|
||||
return WalkResult::skip();
|
||||
}
|
||||
if (auto batch = dyn_cast<SpatScheduledComputeBatch>(op)) {
|
||||
auto ids = op->getAttrOfType<DenseI32ArrayAttr>("coreIds");
|
||||
if (!ids || ids.size() != batch.getLaneCount()) { error = "missing physical batch cores"; okay = false; }
|
||||
else for (auto [lane, id] : llvm::enumerate(ids.asArrayRef())) if (!(okay = core(op, id, lane))) break;
|
||||
return WalkResult::skip();
|
||||
}
|
||||
return WalkResult::advance();
|
||||
});
|
||||
return okay && error.empty();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
PimPeriodicEstimate onnx_mlir::evaluatePimSpatialSchedule(ModuleOp module,
|
||||
const PimInstructionTiming &target, PimPeriodicOptions options) try {
|
||||
if (!target.hasPeriodicTransferTiming() || !target.computeBitwidth)
|
||||
return unavailableCost("unsupported abstract timing contract");
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
Extraction extraction(target, options.workBreakdown, options.omitSynchronization);
|
||||
bool available = extraction.build(module);
|
||||
double extractionMs = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
PimPeriodicEstimate estimate;
|
||||
if (available) estimate = evaluatePimExecution(extraction.program, target, options);
|
||||
else {
|
||||
estimate.cost.reason = extraction.error;
|
||||
estimate.report = llvm::json::Object{{"status", "unavailable"}, {"reason", extraction.error}};
|
||||
if (options.verifyPeriodicState)
|
||||
for (auto &recurrence : estimate.cost.recurrence)
|
||||
recurrence.status = ScheduleRecurrenceEvidence::Unproved;
|
||||
}
|
||||
auto &report = estimate.report;
|
||||
auto &cost = estimate.cost;
|
||||
cost.timing.extractionSeconds = extractionMs / 1000;
|
||||
if (available || extraction.loweringSupport == StaticLoweringSupport::Unsupported)
|
||||
cost.loweringSupport = extraction.loweringSupport;
|
||||
if (available && options.workBreakdown) {
|
||||
PimPeriodicOptions sensitivity;
|
||||
sensitivity.ignoreLocalCopies = true;
|
||||
auto withoutCopies = analyzePimExecution(extraction.program, target, sensitivity);
|
||||
if (auto *queue = withoutCopies.getObject("memory_controller"))
|
||||
report["without_local_copy_work"] = std::move(*queue);
|
||||
}
|
||||
auto convergence = cost.convergenceProved();
|
||||
auto support = cost.loweringSupported();
|
||||
report["cost_available"] = cost.primary.has_value() && cost.alternative.has_value();
|
||||
report["convergence_proved"] = convergence
|
||||
? llvm::json::Value(*convergence) : llvm::json::Value(nullptr);
|
||||
report["lowering_supported"] = support
|
||||
? llvm::json::Value(*support) : llvm::json::Value(nullptr);
|
||||
std::string failureReason = std::move(cost.reason);
|
||||
cost.reason = "Spatial prediction accuracy has no formal bound";
|
||||
if (!cost.available()) cost.reason = "Spatial queue cost is unavailable";
|
||||
else if (cost.loweringSupport != StaticLoweringSupport::Supported)
|
||||
cost.reason = "Spatial lowering support is unproved";
|
||||
else if (convergence != true)
|
||||
cost.reason = "complete-state recurrence is unproved under one or both arbitration policies";
|
||||
if (!extraction.loweringReason.empty()) cost.reason = extraction.loweringReason;
|
||||
if (!failureReason.empty()) cost.reason = std::move(failureReason);
|
||||
report["lowering_support_scope"] = "static operation and transfer contract; final backend verification is required";
|
||||
if (!extraction.loweringReason.empty()) report["lowering_reason"] = extraction.loweringReason;
|
||||
report["safe_for_selection"] = false;
|
||||
report["diagnostic_only"] = true;
|
||||
report["error_bound_available"] = false;
|
||||
report["extraction_ms"] = extractionMs;
|
||||
report["visited_operations"] = extraction.visited;
|
||||
if (!options.workBreakdown) return estimate;
|
||||
report["constant_load_sites"] = extraction.constantLoads;
|
||||
uint64_t workNs = 0, records = 0, constantRequests = 0, constantBytes = 0;
|
||||
constexpr const char *workClassNames[] = {
|
||||
"matrix", "vector", "local_copy", "fill", "vector_copy", "scalar_issue"};
|
||||
std::array<uint64_t, std::size(workClassNames)> workByClass{};
|
||||
static_assert(Event::ScalarIssue + 1 == std::size(workClassNames));
|
||||
std::array<uint64_t, 7> counts{};
|
||||
std::map<uint64_t, uint64_t> readSizes;
|
||||
std::function<void(const Sequence &, uint64_t)> summarize =
|
||||
[&](const Sequence &sequence, uint64_t multiplier) {
|
||||
for (const Event &event : sequence) {
|
||||
++records;
|
||||
if (event.kind == Event::Repeat) summarize(event.body, mul(multiplier, event.amount));
|
||||
else {
|
||||
counts[event.kind] = add(counts[event.kind], multiplier);
|
||||
if (event.kind == Event::Work) {
|
||||
workNs = add(workNs, mul(multiplier, event.amount));
|
||||
switch (event.workClass) {
|
||||
case Event::Matrix:
|
||||
case Event::Vector:
|
||||
case Event::LocalCopy:
|
||||
case Event::Fill:
|
||||
case Event::VectorCopy:
|
||||
case Event::ScalarIssue:
|
||||
workByClass[event.workClass] = add(workByClass[event.workClass], mul(multiplier, event.amount));
|
||||
break;
|
||||
default: throw pim_timing::Unrepresentable{"unsupported execution work class"};
|
||||
}
|
||||
} else if (event.kind == Event::Load) {
|
||||
readSizes[event.amount] = add(readSizes[event.amount], multiplier);
|
||||
if (event.constant) {
|
||||
constantRequests = add(constantRequests, multiplier);
|
||||
constantBytes = add(constantBytes, mul(multiplier, event.amount));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const Sequence &sequence : extraction.program) summarize(sequence, 1);
|
||||
report["compute_and_local_work_ns"] = workNs;
|
||||
llvm::json::Array classes;
|
||||
for (uint64_t value : workByClass) classes.push_back(value);
|
||||
llvm::json::Array columns;
|
||||
for (const char *name : workClassNames) columns.push_back(name);
|
||||
report["work_class_columns"] = std::move(columns);
|
||||
report["work_class_ns"] = std::move(classes);
|
||||
llvm::json::Object eventCounts;
|
||||
const char *names[] = {"work_chunks", "load", "store", "send", "receive", "sync", "wait"};
|
||||
for (size_t i = 0; i < counts.size(); ++i) eventCounts[names[i]] = counts[i];
|
||||
report["event_counts"] = std::move(eventCounts);
|
||||
report["compact_records"] = records;
|
||||
report["constant_read_requests"] = constantRequests;
|
||||
report["constant_read_bytes"] = constantBytes;
|
||||
llvm::json::Array sizes;
|
||||
for (auto [bytes, count] : readSizes)
|
||||
sizes.push_back(llvm::json::Object{{"bytes", bytes}, {"requests", count}});
|
||||
report["read_sizes"] = std::move(sizes);
|
||||
llvm::json::Object gaps;
|
||||
for (const auto &[name, count] : extraction.gaps) gaps[name] = count;
|
||||
report["unresolved_decisions"] = std::move(gaps);
|
||||
report["omitted_effects"] = llvm::json::Array{"scalar register setup", "indirect output collection",
|
||||
"host slice splitting and folding", "copy forwarding and local reuse legality"};
|
||||
report["analysis_ms"] = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
return estimate;
|
||||
} catch (const pim_timing::Unrepresentable &failure) {
|
||||
return unavailableCost(failure.reason);
|
||||
}
|
||||
|
||||
llvm::json::Object onnx_mlir::analyzePimSpatialSchedule(ModuleOp module,
|
||||
const PimInstructionTiming &target, PimPeriodicOptions options) {
|
||||
return evaluatePimSpatialSchedule(module, target, options).report;
|
||||
}
|
||||
|
||||
llvm::json::Object onnx_mlir::analyzePimSpatialSynchronizationAblation(ModuleOp module) {
|
||||
auto timing = getPimInstructionTiming();
|
||||
auto contract = getPimPeriodicTimingContract();
|
||||
if (!contract) return unavailableCost(llvm::toString(contract.takeError())).report;
|
||||
timing.matrixCellBits = *contract;
|
||||
PimPeriodicOptions options;
|
||||
options.omitSynchronization = true;
|
||||
options.verifyPeriodicState = true;
|
||||
options.measureTime = true;
|
||||
auto result = evaluatePimSpatialSchedule(module, timing, options);
|
||||
result.report["diagnostic_only"] = true;
|
||||
result.report["used_for_selection"] = false;
|
||||
result.report["cost_model_program"] = "synchronization-omitted";
|
||||
return std::move(result.report);
|
||||
}
|
||||
|
||||
void onnx_mlir::configurePimScheduleCosts(spatial::SchedulingTarget &target,
|
||||
PimInstructionTiming timing) {
|
||||
// The stage-zero entry barrier joins the previous generation's work.
|
||||
target.estimatePipelineDependencySpan = [](llvm::ArrayRef<Cost> spans) {
|
||||
return spans.empty() ? Cost{0} : spans.front();
|
||||
};
|
||||
auto contract = getPimPeriodicTimingContract();
|
||||
if (contract) timing.matrixCellBits = *contract;
|
||||
auto hardware = std::make_shared<const PimInstructionTiming>(std::move(timing));
|
||||
target.reportPeriodicSchedule = [hardware](const spatial::ComputeGraph &graph,
|
||||
const spatial::ScheduledComputeMaterializationResult &materialization,
|
||||
const spatial::DeferredTransferPlan &transfers,
|
||||
const spatial::DeferredBoundaryPlan &boundaries) {
|
||||
dumpPeriodicScheduleEstimate(graph, materialization, transfers, boundaries, *hardware);
|
||||
};
|
||||
if (!contract) target.wholeScheduleCostUnavailable = llvm::toString(contract.takeError());
|
||||
if (!hardware->hasPeriodicTransferTiming())
|
||||
target.wholeScheduleCostUnavailable = "target has no supported queue timing contract";
|
||||
if (!target.wholeScheduleCostUnavailable.empty()) return;
|
||||
target.estimateRealizedScheduleCost = [hardware](mlir::ModuleOp module,
|
||||
llvm::json::Object &summary) {
|
||||
PimPeriodicOptions options;
|
||||
options.workBreakdown = pimPeriodicDiagnostics;
|
||||
options.measureTime = true;
|
||||
options.verifyPeriodicState = true;
|
||||
options.searchGuidance = true;
|
||||
auto estimate = evaluatePimSpatialSchedule(module, *hardware, options);
|
||||
auto cost = std::move(estimate.cost);
|
||||
summary = std::move(estimate.report);
|
||||
if (estimate.queue)
|
||||
summary["interval_source"] = cost.convergenceProved() == true
|
||||
? "complete-state recurrence under both arbitration policies"
|
||||
: "recurrence is unproved under one or both arbitration policies";
|
||||
summary["cost_available"] = cost.available();
|
||||
return cost;
|
||||
};
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "PimPeriodicAnalysis.hpp"
|
||||
#include "mlir/IR/BuiltinOps.h"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
void configurePimScheduleCosts(spatial::SchedulingTarget &target, PimInstructionTiming timing);
|
||||
|
||||
// Read-only, target-specific work extraction. No target dialect is constructed.
|
||||
PimPeriodicEstimate evaluatePimSpatialSchedule(mlir::ModuleOp module,
|
||||
const PimInstructionTiming &target, PimPeriodicOptions options = {});
|
||||
llvm::json::Object analyzePimSpatialSchedule(mlir::ModuleOp module,
|
||||
const PimInstructionTiming &target, PimPeriodicOptions options = {});
|
||||
llvm::json::Object analyzePimSpatialSynchronizationAblation(mlir::ModuleOp module);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -1,37 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
|
||||
namespace onnx_mlir::pim_timing {
|
||||
|
||||
struct Unrepresentable { const char *reason; };
|
||||
|
||||
// Optional timing queries must fail without wrapping or terminating compilation.
|
||||
struct Arithmetic {
|
||||
static constexpr uint64_t limit = std::numeric_limits<int64_t>::max();
|
||||
unsigned long long add(uint64_t a, uint64_t b) const {
|
||||
if (a > limit || b > limit - a) throw Unrepresentable{"timing addition overflow"};
|
||||
return a + b;
|
||||
}
|
||||
unsigned long long multiply(uint64_t a, uint64_t b) const {
|
||||
if (a > limit || b > limit || (a && b > limit / a))
|
||||
throw Unrepresentable{"timing multiplication overflow"};
|
||||
return a * b;
|
||||
}
|
||||
unsigned long long subtract(uint64_t a, uint64_t b) const {
|
||||
if (a > limit || b > a) throw Unrepresentable{"timing subtraction underflow"};
|
||||
return a - b;
|
||||
}
|
||||
unsigned long long divideUp(uint64_t a, uint64_t b) const {
|
||||
if (!b || a > limit || b > limit) throw Unrepresentable{"unrepresentable timing division"};
|
||||
return a / b + (a % b != 0);
|
||||
}
|
||||
};
|
||||
inline constexpr Arithmetic arithmetic{};
|
||||
inline uint64_t add(uint64_t a, uint64_t b) { return arithmetic.add(a, b); }
|
||||
inline uint64_t mul(uint64_t a, uint64_t b) { return arithmetic.multiply(a, b); }
|
||||
inline uint64_t sub(uint64_t a, uint64_t b) { return arithmetic.subtract(a, b); }
|
||||
inline uint64_t ceil(uint64_t a, uint64_t b) { return arithmetic.divideUp(a, b); }
|
||||
|
||||
} // namespace onnx_mlir::pim_timing
|
||||
@@ -5,7 +5,7 @@ add_public_tablegen_target(ONNXToSpatialIncGen)
|
||||
add_pim_library(OMONNXToSpatial
|
||||
Patterns.cpp
|
||||
CompileTime.cpp
|
||||
Passes/Analyses/ONNXToSpatialVerifier.cpp
|
||||
ONNXToSpatialVerifier.cpp
|
||||
Patterns/Pre.cpp
|
||||
Patterns/Post.cpp
|
||||
Patterns/Math/Conv.cpp
|
||||
@@ -26,14 +26,14 @@ add_pim_library(OMONNXToSpatial
|
||||
Patterns/Tensor/Slice.cpp
|
||||
Patterns/Tensor/Split.cpp
|
||||
Patterns/Tensor/Transpose.cpp
|
||||
Passes/Transforms/ONNXToSpatialPass.cpp
|
||||
Passes/Analyses/SpatialLayoutCapabilities.cpp
|
||||
Passes/Transforms/SpatialLayoutPlanningPass.cpp
|
||||
Passes/Transforms/SpatialPlanLoweringPatterns.cpp
|
||||
Passes/Transforms/LowerSpatialPlansPass.cpp
|
||||
ONNXToSpatialPass.cpp
|
||||
SpatialLayoutCapabilities.cpp
|
||||
SpatialLayoutPlanningPass.cpp
|
||||
LowerSpatialPlansPass.cpp
|
||||
Common/AttributeUtils.cpp
|
||||
Common/BiasAddUtils.cpp
|
||||
Common/ComputeRegionBuilder.cpp
|
||||
Common/ContractionMaterialization.cpp
|
||||
Common/ContractionPlanning.cpp
|
||||
Common/MatrixProductLowering.cpp
|
||||
Common/RowStripLayoutUtils.cpp
|
||||
|
||||
@@ -249,7 +249,7 @@ auto createEmptySpatGraphComputeBatch(RewriterT& rewriter,
|
||||
if (laneCount <= 0 || laneCount > std::numeric_limits<int32_t>::max())
|
||||
return mlir::FailureOr<spatial::SpatGraphComputeBatch>(mlir::failure());
|
||||
|
||||
auto laneCountAttr = pim::getCheckedI32Attr(rewriter, loc, laneCount, "Spatial compute_batch lane count");
|
||||
auto laneCountAttr = pim::getCheckedI32Attr(rewriter, loc, laneCount, "spatial compute_batch lane count");
|
||||
if (mlir::failed(laneCountAttr))
|
||||
return mlir::FailureOr<spatial::SpatGraphComputeBatch>(mlir::failure());
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#include "ContractionMaterialization.hpp"
|
||||
|
||||
#include "src/Accelerators/PIM/Common/IR/ConstantUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Conversion/ONNXToSpatial/CompileTime.hpp"
|
||||
#include "MatrixProductLowering.hpp"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
mlir::Value materializePaddedContractionInput(
|
||||
mlir::Value input,
|
||||
mlir::RankedTensorType paddedType,
|
||||
mlir::PatternRewriter& rewriter,
|
||||
mlir::Location loc) {
|
||||
return createPaddedInputCompute(input, paddedType, rewriter, loc);
|
||||
}
|
||||
|
||||
mlir::FailureOr<mlir::Value> materializeTransposedContractionConstant(
|
||||
mlir::Value input,
|
||||
mlir::RankedTensorType resultType,
|
||||
llvm::ArrayRef<int64_t> permutation,
|
||||
mlir::PatternRewriter& rewriter,
|
||||
mlir::Location loc) {
|
||||
auto denseAttr = getHostConstDenseElementsAttr(input);
|
||||
auto inputType = denseAttr ? mlir::dyn_cast<mlir::RankedTensorType>(denseAttr.getType()) : nullptr;
|
||||
if (!inputType || !inputType.hasStaticShape() || !resultType || !resultType.hasStaticShape()
|
||||
|| inputType.getRank() != resultType.getRank())
|
||||
return mlir::failure();
|
||||
|
||||
auto transposedAttr = transposeDenseElementsAttr(denseAttr, permutation);
|
||||
if (mlir::failed(transposedAttr) || transposedAttr->getType() != resultType)
|
||||
return mlir::failure();
|
||||
|
||||
return getOrCreateConstant(rewriter,
|
||||
rewriter.getInsertionBlock()->getParentOp(),
|
||||
*transposedAttr,
|
||||
resultType);
|
||||
}
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
|
||||
#include "mlir/IR/BuiltinTypes.h"
|
||||
#include "mlir/IR/PatternMatch.h"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
mlir::Value materializePaddedContractionInput(
|
||||
mlir::Value input,
|
||||
mlir::RankedTensorType paddedType,
|
||||
mlir::PatternRewriter& rewriter,
|
||||
mlir::Location loc);
|
||||
|
||||
mlir::FailureOr<mlir::Value> materializeTransposedContractionConstant(
|
||||
mlir::Value input,
|
||||
mlir::RankedTensorType resultType,
|
||||
llvm::ArrayRef<int64_t> permutation,
|
||||
mlir::PatternRewriter& rewriter,
|
||||
mlir::Location loc);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -12,30 +12,56 @@ static int64_t ceilDivide(int64_t value, int64_t divisor) {
|
||||
return divisor == 0 ? 0 : (value + divisor - 1) / divisor;
|
||||
}
|
||||
|
||||
static llvm::SmallVector<int64_t> buildBatchMap(
|
||||
llvm::ArrayRef<int64_t> sourceShape,
|
||||
llvm::ArrayRef<int64_t> outputShape) {
|
||||
llvm::SmallVector<int64_t> map(outputShape.size(), -1);
|
||||
const int64_t offset = outputShape.size() - sourceShape.size();
|
||||
for (int64_t source = 0; source < static_cast<int64_t>(sourceShape.size()); ++source) {
|
||||
const int64_t output = source + offset;
|
||||
if (sourceShape[source] != 1)
|
||||
map[output] = source;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ContractionPlan makeContractionPlan(
|
||||
const ContractionProblem& problem,
|
||||
const spatial::SpatialTargetResources& target,
|
||||
const spatial::SpatialTargetInfo& target,
|
||||
ContractionPlanKind kind,
|
||||
int64_t laneCount,
|
||||
int64_t fragmentRows) {
|
||||
ContractionPlan plan;
|
||||
plan.problem = problem;
|
||||
plan.kind = kind;
|
||||
plan.tileM = std::max<int64_t>(1, target.matrixShape.rows);
|
||||
plan.tileK = std::max<int64_t>(1, target.matrixShape.rows);
|
||||
plan.tileN = std::max<int64_t>(1, target.matrixShape.columns);
|
||||
plan.reductionSlices = std::max<int64_t>(1, ceilDivide(problem.k, plan.tileK));
|
||||
plan.outputTiles = std::max<int64_t>(1, ceilDivide(problem.n, plan.tileN));
|
||||
const int64_t rowsPerLane = std::max<int64_t>(
|
||||
1, fragmentRows != 0 ? fragmentRows : target.matrixShape.rows);
|
||||
plan.rowTiles = std::max<int64_t>(1, ceilDivide(problem.m, plan.tileM));
|
||||
plan.fragmentRows = std::max<int64_t>(
|
||||
1, fragmentRows != 0 ? fragmentRows : plan.tileM);
|
||||
plan.lhsBatchMap = buildBatchMap(problem.lhsBatchShape, problem.outputBatchShape);
|
||||
plan.rhsBatchMap = buildBatchMap(problem.rhsBatchShape, problem.outputBatchShape);
|
||||
|
||||
if (laneCount != 0)
|
||||
plan.laneCount = laneCount;
|
||||
else if (kind == ContractionPlanKind::StaticTiled)
|
||||
plan.laneCount = problem.batch * problem.m * plan.reductionSlices * plan.outputTiles;
|
||||
else if (kind == ContractionPlanKind::GroupedRowDynamicVVD)
|
||||
plan.laneCount = problem.batch * ceilDivide(problem.m, rowsPerLane);
|
||||
plan.laneCount = problem.batch * ceilDivide(problem.m, plan.fragmentRows);
|
||||
else
|
||||
plan.laneCount = problem.batch * problem.m * problem.n;
|
||||
|
||||
plan.expectedMvmCount = kind == ContractionPlanKind::StaticTiled ? plan.laneCount : 0;
|
||||
plan.expectedVvdCount = kind == ContractionPlanKind::StaticTiled ? 0 : plan.laneCount;
|
||||
plan.expectedVectorCount = plan.laneCount * plan.reductionSlices;
|
||||
if (problem.resultElementType && problem.n > 0)
|
||||
plan.physicalFragmentType = mlir::RankedTensorType::get(
|
||||
{plan.fragmentRows, problem.n}, problem.resultElementType);
|
||||
return plan;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
#include "ContractionProblem.hpp"
|
||||
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/SpatialTargetResources.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/SpatialTargetInfo.hpp"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
@@ -13,16 +13,27 @@ enum class ContractionPlanKind {
|
||||
};
|
||||
|
||||
struct ContractionPlan {
|
||||
ContractionProblem problem;
|
||||
ContractionPlanKind kind = ContractionPlanKind::StaticTiled;
|
||||
int64_t tileM = 1;
|
||||
int64_t tileK = 1;
|
||||
int64_t tileN = 1;
|
||||
int64_t fragmentRows = 1;
|
||||
int64_t reductionSlices = 1;
|
||||
int64_t outputTiles = 1;
|
||||
int64_t rowTiles = 1;
|
||||
int64_t laneCount = 0;
|
||||
int64_t expectedMvmCount = 0;
|
||||
int64_t expectedVvdCount = 0;
|
||||
int64_t expectedVectorCount = 0;
|
||||
llvm::SmallVector<int64_t> lhsBatchMap;
|
||||
llvm::SmallVector<int64_t> rhsBatchMap;
|
||||
mlir::RankedTensorType physicalFragmentType;
|
||||
};
|
||||
|
||||
ContractionPlan makeContractionPlan(
|
||||
const ContractionProblem& problem,
|
||||
const spatial::SpatialTargetResources& target,
|
||||
const spatial::SpatialTargetInfo& target,
|
||||
ContractionPlanKind kind,
|
||||
int64_t laneCount = 0,
|
||||
int64_t fragmentRows = 0);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user