Skip to content

Commit 21789e3

Browse files
authored
Merge branch 'master' into tensor-as-long-pr
2 parents e0052c0 + 07e8148 commit 21789e3

File tree

14 files changed

+1652
-61
lines changed

14 files changed

+1652
-61
lines changed

modules/custom_operations/tests/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ onnx
33
tensorboard
44
pytest
55
# open3d==0.16.0 - need to update with new release
6+
onnxscript==0.5.4

modules/custom_operations/tests/run_tests.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,17 @@ def test_fft(shape, inverse, centered, test_onnx, dims):
4444
from examples.fft.export_model import export
4545

4646
if len(shape) == 3 and dims != [1] or \
47-
len(shape) == 4 and dims == [2, 3] or \
48-
len(shape) == 5 and dims == [1] or \
47+
len(shape) == 4 and dims in ([1, 2], [2, 3]) or \
48+
len(shape) == 5 and dims in ([1], [1, 2], [2, 3]) or \
4949
centered and len(dims) != 2:
5050
pytest.skip("unsupported configuration")
5151

52+
if len(shape) == 4 and dims == [1]:
53+
pytest.skip("Custom FFT executed but there is accuracy error, requires FFT::evaluate fix")
54+
55+
5256
inp, ref = export(shape, inverse, centered, dims)
53-
run_test(inp, ref, test_onnx=test_onnx)
57+
run_test(inp, ref, test_onnx=test_onnx)
5458

5559

5660
@pytest.mark.parametrize("shape", [[3, 2, 4, 8, 2], [3, 1, 4, 8, 2]])
@@ -86,6 +90,7 @@ def test_sparse_conv_transpose(in_channels, filters, kernel_size, out_pos):
8690
run_test(inp, ref, test_onnx=True, threshold=1e-4)
8791

8892

93+
@pytest.mark.skip(reason="Exported model do not contains calculate_grid operator")
8994
def test_calculate_grid():
9095
from examples.calculate_grid.export_model import export
9196
inp, ref = export(num_points=10, max_grid_extent=5)

modules/custom_operations/user_ie_extensions/fft.cpp

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,10 @@ void FFT::validate_and_infer_types() {
112112
}
113113

114114
std::shared_ptr<ov::Node> FFT::clone_with_new_inputs(const ov::OutputVector& new_args) const {
115-
OPENVINO_ASSERT(new_args.size() == 2, "Incorrect number of new arguments");
115+
const ov::Dimension exp_no_inputs{2};
116+
OPENVINO_ASSERT(exp_no_inputs.compatible(new_args.size()),
117+
"Incorrect number of new arguments, provided: ",
118+
new_args.size());
116119
return std::make_shared<FFT>(new_args, inverse, centered);
117120
}
118121

@@ -128,15 +131,15 @@ bool FFT::visit_attributes(ov::AttributeVisitor& visitor) {
128131

129132
bool FFT::evaluate(ov::TensorVector& outputs, const ov::TensorVector& inputs) const {
130133
//const_cast because the cvSetData use user pointer as non-const, should be ok as it looks like input data
131-
float *inpData = reinterpret_cast<float *>(const_cast<void*>(inputs[0].data()));
134+
auto *inpData = const_cast<float*>(inputs[0].data<float>());
132135

133136
if (inputs[1].get_element_type() != ov::element::i32)
134137
OPENVINO_THROW("Unexpected dims type: " + inputs[1].get_element_type().to_string());
135138

136-
const int32_t *signalDimsData = reinterpret_cast<const int32_t *>(inputs[1].data());
137-
float* outData = reinterpret_cast<float*>(outputs[0].data());
139+
auto *signalDimsData = inputs[1].data<int32_t>();
140+
auto *outData = outputs[0].data<float>();
138141
std::vector<size_t> dims = inputs[0].get_shape();
139-
const size_t numSignalDims = inputs[1].get_shape()[0];
142+
const size_t numSignalDims = inputs[1].get_shape().empty() ? 1: inputs[1].get_shape().size();
140143

141144
if (!((dims.size() == 3 && numSignalDims == 1 && signalDimsData[0] == 1) ||
142145
(dims.size() == 4 && ((numSignalDims == 1 && signalDimsData[0] == 1) ||

modules/custom_operations/user_ie_extensions/ov_extension.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@
2929
# include "fft.hpp"
3030
# define FFT_EXT \
3131
std::make_shared<ov::OpExtension<TemplateExtension::FFT>>(), \
32-
std::make_shared<ov::frontend::OpExtension<TemplateExtension::FFT>>(),
32+
std::make_shared<ov::frontend::OpExtension<TemplateExtension::FFT>>( \
33+
"DFT", \
34+
std::map<std::string, std::string>{ {"centered", "onesided"}, {"inverse", "inverse"} }),
3335
#else
3436
# define FFT_EXT
3537
#endif

modules/genai_optimizations/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ This module provides experimental optimizations for GenAI models in PyTorch. The
66

77
- Text Generation Using LLMs
88
- Visual language text generation
9+
- Reasoning and Problem Solving
910

1011
## Supported Generative AI Optimization Methods
1112

@@ -34,6 +35,14 @@ This module provides experimental optimizations for GenAI models in PyTorch. The
3435
Paper: https://arxiv.org/pdf/2306.14048
3536
- **SnapKV Mode** – Modifies the *H2O* approach by computing token importance within a small sliding window of the most recent queries during the prefill stage, then reverting to the H2O strategy during decoding. The authors observed that only a small subset of prompt tokens is sufficient for accurate response generation.
3637
Paper: https://arxiv.org/pdf/2404.14469
38+
- **RKV Mode** - Computes token importance scores based on attention weights over a sliding window of the most recent queries during both the prefill and decode stages. Importance scores are stabilized using per-token max-pooling and then averaged across attention heads.
39+
40+
Refined modes enhance standard eviction strategies by selecting the most representative tokens or blocks from the evictable (intermediate) region. These methods aim to balance contextual importance with redundancy reduction to optimize cache efficiency. If `refined_algorithm` is enabled but `refined_tokens` is not specified or set to 0, the number of refined tokens is determined dynamically as part of the intermediate token budget. Budget for primary algorithm is allocated by selecting the minimal number of tokens or groups that together capture at least 90% of the total attention mass, ensuring that all high-importance tokens are retained. For the remaining eviction budget, each token’s dissimilarity is computed relative to the already retained set, promoting information diversity and reducing redundancy.
41+
42+
Supported refined modes:
43+
- **KVCrush Mode** - Selects representative blocks based on diversity rather than raw importance. This is achieved by generating binary indicators for each token, constructing an anchor point (reference pattern) using one of several modes: `random`, `zeros`, `ones`, `mean`, `alternate`, and selecting blocks with the highest Hamming distance to the anchor point.
44+
Paper: https://arxiv.org/pdf/2503.00022
45+
- **DiverseKV Mode** – Implements a dynamic redundancy scoring mechanism to identify and de-prioritize repetitive tokens based on cosine similarity of key vectors with already retained tokens. Key vectors are normalized, and cosine similarities are computed with diagonal values zeroed to avoid self-similarity. Similarities are thresholded on a per-head basis—only values greater than or equal to the mean similarity for each head are kept and then aggregated across heads. For the remaining eviction budget, each token or group's dissimilarity to already retained tokens or groups is calculated. Tokens/groups with the highest dissimilarity scores are retained, maximizing contextual diversity while reducing redundancy.
3746

3847
## Supported and tested models
3948

@@ -53,6 +62,12 @@ Multimodal Large Language Models:
5362
- [Qwen/Qwen2.5-VL-3B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct)
5463
- [Qwen/Qwen2-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct)
5564

65+
Large Reasoning Models:
66+
67+
- [deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B)
68+
- [Qwen/Qwen3-1.7B](https://huggingface.co/Qwen/Qwen3-1.7B)
69+
- [microsoft/Phi-4-mini-reasoning](https://huggingface.co/microsoft/Phi-4-mini-reasoning)
70+
5671
## Prerequisites
5772

5873
Before running algorithms, ensure you have **Python 3.10+** installed and set up your environment.

modules/genai_optimizations/benchmarks/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ This [example](./longbench.py) demonstrates how to evaluate and optimize LLMs us
1010

1111
Sparse attention speeds up the prefill stage in LLMs by attending only to the most relevant query-key blocks. Static patterns like Tri-Shape and dynamic mechanisms like XAttention reduce memory and computation without significant accuracy loss, enabling efficient handling of long prompts.
1212

13+
KV-Cache Token Eviction accelerates the decoding stage in LLMs by removing less important cached tokens while preserving those essential for contextual understanding, allowing efficient long-sequence inference under constrained memory.
14+
1315
### Run Example
1416

1517
```bash
@@ -100,3 +102,32 @@ This will automatically:
100102
- Evaluate the model and report the score
101103

102104
</details>
105+
106+
<details>
107+
<summary><b>Large Reasoning Models Optimization Example: MATH500 and GSM8K Benchmarks</b></summary>
108+
109+
This [example](./math500_gsm_bench.py) demonstrates how to evaluate and optimize LRMs using the KV-Cache Token Eviction algorithm. The example leverages [MATH500](https://huggingface.co/datasets/HuggingFaceH4/MATH-500) and [GSM8K](https://huggingface.co/datasets/openai/gsm8k) datasets.
110+
MATH500 contains a subset of 500 problems from the [MATH](https://github.com/hendrycks/math) benchmark, originally introduced in OpenAI’s Let’s Verify Step by Step paper. The subset covers six domains: algebra, geometry, intermediate algebra, number theory, precalculus, and probability.
111+
GSM8K (Grade School Math 8K) is a dataset of 8,500 high-quality, linguistically diverse grade-school math word problems. While the problems are conceptually simple, they often require multi-step reasoning, making them challenging for state-of-the-art language models due to the high diversity of problems.
112+
113+
114+
### Run Example
115+
116+
```bash
117+
python math500_gsm_bench.py \
118+
--dataset MATH500 \
119+
--model deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B \
120+
--max_tokens 5000 \
121+
--max_examples 100 \
122+
--enable_eviction \
123+
--algorithm rkv \
124+
--granularity per_group \
125+
--intermediate_tokens 512
126+
```
127+
This will automatically:
128+
129+
- Download the selected model and dataset
130+
- Apply token eviction during the decoding stage
131+
- Evaluate the model and report the score
132+
133+
</details>

0 commit comments

Comments
 (0)