Skip to content

Commit 2157bec

Browse files
committed
Rebase and add vector normalization
1 parent 6bdec68 commit 2157bec

3 files changed

Lines changed: 25 additions & 7 deletions

File tree

packages/react-native-executorch/common/rnexecutorch/data_processing/Numerical.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "Numerical.h"
22

33
#include <algorithm>
4+
#include <cmath>
45
#include <numeric>
56

67
namespace rnexecutorch::numerical {
@@ -16,4 +17,15 @@ void softmax(std::vector<float> &v) {
1617
x /= sum;
1718
}
1819
}
20+
void normalizeVector(std::vector<float> &v) {
21+
float norm = 0.0;
22+
for (float value : v) {
23+
norm += value * value;
24+
}
25+
norm = sqrt(norm);
26+
27+
for (float &value : v) {
28+
value /= norm;
29+
}
30+
}
1931
} // namespace rnexecutorch::numerical

packages/react-native-executorch/common/rnexecutorch/data_processing/Numerical.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44

55
namespace rnexecutorch::numerical {
66
void softmax(std::vector<float> &v);
7+
void normalizeVector(std::vector<float> &v);
78
} // namespace rnexecutorch::numerical

packages/react-native-executorch/common/rnexecutorch/models/image_embeddings/ImageEmbeddings.cpp

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
#include "ImageEmbeddings.h"
22

3-
#include <cstdint>
43
#include <executorch/extension/tensor/tensor.h>
5-
#include <iostream>
6-
#include <rnexecutorch/Log.h>
74
#include <rnexecutorch/data_processing/ImageProcessing.h>
8-
5+
#include <rnexecutorch/data_processing/Numerical.h>
96
namespace rnexecutorch {
107

118
ImageEmbeddings::ImageEmbeddings(
@@ -48,11 +45,19 @@ ImageEmbeddings::generate(std::string imageSource) {
4845

4946
auto &outputTensor = outputs.at(0).toTensor();
5047
auto sizesRaw = outputTensor.sizes();
51-
std::vector<int32_t> sizes =
52-
std::vector<int32_t>(sizesRaw.begin(), sizesRaw.end());
48+
auto sizes = std::vector<int32_t>(sizesRaw.begin(), sizesRaw.end());
5349
size_t bufferSize = outputTensor.numel() * outputTensor.element_size();
5450
auto buffer = std::make_shared<OwningArrayBuffer>(bufferSize);
55-
std::memcpy(buffer->data(), outputTensor.const_data_ptr(), bufferSize);
51+
52+
std::span<const float> outputTensorSpan(
53+
static_cast<const float *>(outputTensor.const_data_ptr()),
54+
outputTensor.numel());
55+
std::vector<float> outputVector(outputTensorSpan.begin(),
56+
outputTensorSpan.end());
57+
58+
numerical::normalizeVector(outputVector);
59+
60+
std::memcpy(buffer->data(), outputVector.data(), bufferSize);
5661
auto jsTensor = std::make_shared<JSTensorViewOut>(
5762
sizes, outputTensor.scalar_type(), buffer);
5863

0 commit comments

Comments
 (0)