Skip to content

Generate metrics from model's layers #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 38 commits
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
134c3b8
Initial generate_layers_metrics version
flaviabeo Jun 12, 2025
ce42e32
Initial version of inference with pre and post hooks
flaviabeo Jun 16, 2025
c48e271
Checks output type
flaviabeo Jun 17, 2025
f78909d
Convert tensor method and save files
flaviabeo Jun 17, 2025
9b4853c
Adds Cosine Similarity + prefix files
flaviabeo Jun 18, 2025
f212b8a
Adds dim=1 to Cosine sim
flaviabeo Jun 19, 2025
c9c54a4
Removes extra space
flaviabeo Jun 20, 2025
315ff35
Adds layer IO mode to get_thresholds
flaviabeo Jun 30, 2025
09c76c2
Changes model_id to model_path
flaviabeo Jul 1, 2025
3afcac2
Fixes model_path assignment
flaviabeo Jul 1, 2025
3ce8e9c
Save metrics to json
flaviabeo Jul 1, 2025
55b7811
Fix json results assignment
flaviabeo Jul 1, 2025
54017ac
Adds python logger
flaviabeo Jul 1, 2025
ace8dfe
Fix logs
flaviabeo Jul 1, 2025
9934746
Adds env variable for LOG LEVEL
flaviabeo Jul 2, 2025
5e1f043
unsqueeze cosine similarity
flaviabeo Jul 2, 2025
02a01ce
Fix same device for cosine similarity
flaviabeo Jul 2, 2025
c7d5a40
Convert cos sim to list
flaviabeo Jul 2, 2025
3a96397
Test euclidean dist
flaviabeo Jul 2, 2025
d68c52f
Adds sample json output to layer th
flaviabeo Jul 2, 2025
7639b08
Merge branch 'main' into generate_metrics_layers
flaviabeo Jul 2, 2025
eb0b866
Adds logging to th script
flaviabeo Jul 2, 2025
dee632e
Model forward mode
flaviabeo Jul 3, 2025
4576a3c
Adds docs
flaviabeo Jul 3, 2025
dc31192
Fix typos
flaviabeo Jul 3, 2025
be1b8d8
Small detail changes
flaviabeo Jul 3, 2025
3ea4084
Prefix with sequence lenght on files' names
flaviabeo Jul 3, 2025
ee32a6b
Adds output path to the json th
flaviabeo Jul 7, 2025
45b6514
Catch StopIteration error
flaviabeo Jul 7, 2025
a7732e9
Adds docstring to methods
flaviabeo Jul 7, 2025
d35b521
Fix cosine similarity calculation
flaviabeo Jul 8, 2025
d90b227
Fix print cpu output shape
flaviabeo Jul 8, 2025
a6894ce
Order result JSON for th
flaviabeo Jul 8, 2025
e41bf20
Review fixes required
flaviabeo Jul 8, 2025
86b5fea
Adds layer mode header
flaviabeo Jul 8, 2025
41b849a
Includes head sub-tensors values
flaviabeo Jul 8, 2025
db9b9fe
Metric list shape
flaviabeo Jul 8, 2025
d4aa817
Metric list shape
flaviabeo Jul 8, 2025
b8d900c
First part of review fixes requested
flaviabeo Jul 9, 2025
1c800e3
Help argsparse added
flaviabeo Jul 9, 2025
f74cbbc
Adds docs about the arg parse
flaviabeo Jul 9, 2025
c8aed03
Modifies the th output json to all dicts
flaviabeo Jul 9, 2025
fc249c5
Moves methods to utils
flaviabeo Jul 9, 2025
0f7f697
Small fix
flaviabeo Jul 9, 2025
12d8c9e
Avg and mean for cosine similarity
flaviabeo Jul 9, 2025
de8ee15
Fix avg and mean dict
flaviabeo Jul 9, 2025
fbafe1d
Fix avg and mean dict
flaviabeo Jul 9, 2025
96ed494
Fix find files with cos sim
flaviabeo Jul 9, 2025
5ae39a1
Fix layer names in json
flaviabeo Jul 9, 2025
b10ed9d
Updates sample result JSON
flaviabeo Jul 9, 2025
ced6d31
Changes layer stack structure to dict
flaviabeo Jul 9, 2025
a6f84bc
Adds zero values handling
flaviabeo Jul 10, 2025
2fe9124
Merge branch 'main' into generate_metrics_layers
flaviabeo Jul 10, 2025
8b5a64f
Fix infer method docstring
flaviabeo Jul 10, 2025
b6bf42d
Adds model path and saves all generate iteractions
flaviabeo Jul 10, 2025
cc42d7d
Save iters and read by layers
flaviabeo Jul 10, 2025
40e5924
Removes unused import
flaviabeo Jul 10, 2025
12946a0
Changes metric list to all generate iters
flaviabeo Jul 10, 2025
526c6d5
Improves layers th data structure
flaviabeo Jul 10, 2025
28c44f8
Fix th json
flaviabeo Jul 11, 2025
d2e3d98
Add configurable sample requests to prepare inputs
flaviabeo Jul 11, 2025
acde4fd
Changes 0 values to small values (avoid nan)
flaviabeo Jul 14, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
405 changes: 405 additions & 0 deletions scripts/generate_layers_metrics.py

Large diffs are not rendered by default.

110 changes: 110 additions & 0 deletions tests/LAYERS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Layer Metrics Generation

Generate metrics by layers to be used in tests and model enablement debugging.

1. [Generate metrics by layer in GPU](./LAYERS.md#1-generate-metrics-by-layer)
2. [Get Thresholds](./LAYERS.md#2-get-thresholds)
3. [Apply metrics where needed](./LAYERS.md#3-apply-the-thresholds-where-needed)

The steps as part of the diagram below:
![generate flow](./resources/assets/metrics_fms_deepview_integration.zoom.png)
To see the full integration with other debugging tools, check [item 3](./LAYERS.md#3-apply-the-thresholds-where-needed).

## 1. Generate Metrics by Layer

The idea is to run, the prompts through the model with the pre- and post-hooks added, and then get the metrics for the outputs intercepted by each layer, as in this diagram. Then we can have a baseline with CPU/GPU for a failure threshold in AIU tests. Same idea as the [test_decoders.py](https://github.com/foundation-model-stack/aiu-fms-testing-utils/blob/main/tests/models/test_decoders.py), but for each layer. This way we can measure the discrepancies for the outputs and use the thresholds for detailed debugging problems in AIU.

![metrics generation by layer](./resources/assets/metrics_generation_layers.png)

The script [generate_layers_metrics.py](../scripts/generate_layers_metrics.py) requires the following environment variables:

```bash
export MODEL_PATHS=ibm-granite/granite-3.2-8b-instruct
export BATCH_SIZES=1
export SEQ_LENGTHS=64
export MAX_NEW_TOKENS=128
export OUTPUT_PATH=/tmp/output/granite
```

These variables support single and array values.

The argument required for this script is the `--mode`, which is the generation mode desired for the output; The choices can be `generate` or `model-forward`.
- `generate` uses FMS [generate](../scripts/generate_layers_metrics.py#L118); It’s a high-level API that wraps many operations: forward pass, KV cache logic, sampling or greeting decoding, post-processing.
```python
result = generate(
model,
ids,
max_new_tokens=max_new_tokens,
use_cache=use_cache,
do_sample=do_sample,
max_seq_len=max_seq_len,
timing="e2e",
eos_token_id=None,
contiguous_cache=True,
extra_kwargs={},
)
```
- `model-forward` will call [model.forward](../scripts/generate_layers_metrics.py#L135); Avoids introducing noise from sampling, past key caching, etc.
```python
result = model.forward(
ids,
use_cache=use_cache
)
```

### How to run

Once all is set up, we can generate the CSV metrics:

```bash
cd aiu-fms-testing-utils/tests/resources

mkdir /tmp/output

python3 aiu-fms-testing-utils/scripts/generate_layers_metrics.py --mode generate
```
The files should get created at `/tmp/output` dir:
```bash
ibm-granite--granite-3.2-8b-instruct_max-new-tokens-128_batch-size-1_seq-length-0_dtype-float16--model.base_model.layers7.ln.abs_diff.csv
ibm-granite--granite-3.2-8b-instruct_max-new-tokens-128_batch-size-1_seq-length-0_dtype-float16--model.base_model.layers7.ln.cos_sim.csv
ibm-granite--granite-3.2-8b-instruct_max-new-tokens-128_batch-size-1_seq-length-0_dtype-float16--model.base_model.layers8.attn.dense.abs_diff.csv
ibm-granite--granite-3.2-8b-instruct_max-new-tokens-128_batch-size-1_seq-length-0_dtype-float16--model.base_model.layers8.attn.dense.cos_sim.csv
```

## 2. Get Thresholds

To get the second step of the flow and get the thresholds by layer, run:
```bash
cd /aiu-fms-testing-utils/tests/resources

python3 get_thresholds.py --models ibm-granite/granite-3.2-8b-instruct --metrics abs_diff cos_sim --file_base /tmp/output --layer_io
```
It should print the metric of each layer:
```bash
Layer model.base_model.layers25.attn.in_proj.query avg abs_diff = 2.079996666484281
Layer model.base_model.layers25.attn.in_proj.key avg abs_diff = 1.2256532914682756
Layer model.base_model.layers25.attn.in_proj.value avg abs_diff = 0.8446561344670284
Layer model.base_model.layers25.attn.in_proj avg abs_diff = 0.0
Layer model.base_model.layers25.attn.dense avg abs_diff = 0.23142293885894077
Layer model.base_model.layers25.ff_ln avg abs_diff = 0.9550253005897409
Layer model.base_model.layers25.ff_sub_layer.wg avg abs_diff = 1.2256491705546648
Layer model.base_model.layers25.ff_sub_layer.a avg abs_diff = 0.5235781749861929
Layer model.base_model.layers25.ff_sub_layer.w1 avg abs_diff = 1.2707070667436549
Layer model.base_model.layers25.ff_sub_layer.w2 avg abs_diff = 0.5201997339672954
Layer model.base_model.layers25.ff_sub_layer avg abs_diff = 0.5201997339672954
Layer model.base_model.layers26.ln avg abs_diff = 0.04852477119171675
[...]
Layer model.base_model.layers39.attn.in_proj.query avg cos_sim = 0.999176025390625
Layer model.base_model.layers39.attn.in_proj.key avg cos_sim = 0.9991455078125
Layer model.base_model.layers39.attn.in_proj.value avg cos_sim = 0.9986572265625
Layer model.base_model.layers39.attn.in_proj avg cos_sim = 0.0
Layer model.base_model.layers39.attn.dense avg cos_sim = 0.9987258911132812
```
Also, a JSON file is saved to the same output dir. A sample file can be found at: [sample_layer_th.json](https://github.com/flaviabeo/aiu-fms-testing-utils/blob/generate_metrics_layers/tests/resources/sample_layer_th.json)

## 3. Apply the thresholds where needed

In case of AIU debugging tools, the thresholds will be applied to compare AIU outputs with CPU, and then assert if the differences are within the thresholds generated. Bellow, is an architecture of the full integration:
![full integration](./resources/assets/metrics_fms_deepview_integration.full.png)

The box named `deepview layer debug` has the diagram of how the model layers outputs are generated to be compared against the CPU results. This is important so that the debug tools can catch operations and layers that have issues in their enablement for AIU hardware.
Loading