Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
df762d6
[RNE Rewrite] Add text and image embeddings pipelines
msluszniak Jun 30, 2026
b9f35d8
feat: variable-length text embeddings via get_dynamic_dims
msluszniak Jul 1, 2026
df8d82f
Address review: trim comments, document get_dynamic_dims, add image e…
msluszniak Jul 1, 2026
0f2bb51
Redesign image embeddings demo as CLIP zero-shot classifier
msluszniak Jul 1, 2026
ace0d99
Address review: cache dynamic dims, harden validation, fix edge cases
msluszniak Jul 1, 2026
0fa2742
fix(computer-vision): add JSDoc @param/@returns for skImageToBuffer
msluszniak Jul 2, 2026
6c3ccc4
feat: port get_dynamic_dims range validation onto new model validation
msluszniak Jul 3, 2026
da219cd
refactor(embeddings): pre-allocate static tensors via `as const` array
msluszniak Jul 3, 2026
7e402b9
refactor(model): generic per-method dynamic input shapes
msluszniak Jul 8, 2026
d517725
refactor(embeddings): rename to Embedder/embed, drop domain task exports
msluszniak Jul 8, 2026
de82f79
chore(embeddings): pin all text-embedding models to v0.10.0
msluszniak Jul 9, 2026
928f9f2
refactor(model): address review feedback on embeddings PR
msluszniak Jul 9, 2026
5808925
docs(model-schema): document get_dynamic_dims_<methodName> companion …
msluszniak Jul 10, 2026
37c8ac4
feat(embeddings): add LFM2.5-Embedding-350M with optional prompt support
msluszniak Jul 10, 2026
6a0cd7a
feat(nlp-demo): add LFM2.5 to text embeddings with asymmetric prompts
msluszniak Jul 10, 2026
c8d8255
refactor(embeddings): address review nits
msluszniak Jul 13, 2026
2620a40
feat(nlp): enable MLX text-embedding backend + LFM2.5 MLX demo
msluszniak Jul 13, 2026
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
14 changes: 14 additions & 0 deletions .agents/skills/model-schema-validation/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ The `SymbolicTensor` helper supports specifying **Symbolic Shapes** where intege

---

## ⚙️ Runtime Dynamic Dimensions: the `get_dynamic_dims_<methodName>` companion

`SymbolicTensor` string symbols let the **validator** accept a range of shapes, but an ExecuTorch `.pte`'s metadata only serializes the **static upper bound** of a dynamic dimension — not its active `[min, max, step]` range. So for an input dimension that genuinely varies at runtime (e.g. a text model's sequence length), the model must be **exported with a companion method** that re-exposes the range to the runtime:

* **Name**: `get_dynamic_dims_<methodName>` — e.g. `get_dynamic_dims_forward` for `forward`.
* **Signature**: takes no arguments.
* **Returns**: a list of outputs, one per `Tensor` input of the target method (scalar inputs are skipped), each a **2D `int32` tensor of shape `[rank, 3]`** whose rows are `[min, max, step]` constraints for that input's dimensions — e.g. `[1, 1, 1]` for a fixed dimension and `[1, maxTokens, 1]` for the dynamic one.

At load time the C++ core (`Model::parseDynamicInputShapes`) reads this companion and validates inputs against the range; `model.execute` then accepts tensors at their exact runtime length. **Without the companion, a method falls back to exact per-dimension validation** — it only accepts the single shape it was exported with. So a `.pte` whose metadata reports `[1, 512]` but is meant to accept `[1, 1..512]` MUST ship `get_dynamic_dims_forward`, or variable-length inputs are rejected at runtime.

This is an **export-side contract** (the export-scripts repo provides a `build_dynamic_dims_program` helper that emits the companion). The TypeScript task only declares the symbol via `SymbolicTensor` and reads the resulting upper bound from `meta.inputTensorMeta`.

---

## 📋 Common Validation Recipes

### 1. Classification
Expand Down
7 changes: 7 additions & 0 deletions apps/computer-vision/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export default function Layout() {
title: 'Classification',
}}
/>
<Drawer.Screen
name="imageEmbeddings/index"
options={{
drawerLabel: 'Image Embeddings',
title: 'Image Embeddings',
}}
/>
<Drawer.Screen
name="detection/index"
options={{
Expand Down
9 changes: 7 additions & 2 deletions apps/computer-vision/app/classification/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, Platform } from 'react-native';
import { commonStyles, ColorPalette } from '../../theme';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { commonStyles, ColorPalette, theme } from '../../theme';
import { useImage } from '@shopify/react-native-skia';
import { useClassifier, models } from 'react-native-executorch';
import ScreenWrapper from '../../components/ScreenWrapper';
Expand Down Expand Up @@ -28,6 +29,7 @@ const MODEL_OPTIONS: ModelOption[] = [
];

function ClassificationContent() {
const insets = useSafeAreaInsets();
const [selectedModel, setSelectedModel] = useState<any>(MODEL_OPTIONS[0].value);
const [imageUri, setImageUri] = useState<string | null>(null);
const [isProcessing, setIsProcessing] = useState(false);
Expand Down Expand Up @@ -97,7 +99,10 @@ function ClassificationContent() {
return (
<ScrollView
style={commonStyles.container}
contentContainerStyle={commonStyles.contentContainer}
contentContainerStyle={[
commonStyles.contentContainer,
{ paddingBottom: insets.bottom + theme.spacing.large },
]}
>
<Text style={commonStyles.description}>
Upload or capture an image to identify objects using a classifier.
Expand Down
250 changes: 250 additions & 0 deletions apps/computer-vision/app/imageEmbeddings/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, TextInput, TouchableOpacity } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { commonStyles, ColorPalette } from '../../theme';
import { useImage } from '@shopify/react-native-skia';
import { useImageEmbedder, useTextEmbedder, models } from 'react-native-executorch';
import ScreenWrapper from '../../components/ScreenWrapper';
import { getImage, skImageToBuffer } from '../../utils';
import { ModelPicker, type ModelOption } from '../../components/ModelPicker';
import { ImageViewport } from '../../components/ImageViewport';
import { ModelStatus } from '../../components/ModelStatus';
import { LatencyIndicator } from '../../components/LatencyIndicator';
import { Button } from '../../components/Button';

const IMAGE_MODEL_OPTIONS: ModelOption[] = [
{
label: 'CLIP ViT-B/32 (INT8)',
value: models.imageEmbeddings.CLIP_VIT_BASE_PATCH32.XNNPACK_INT8,
},
{
label: 'CLIP ViT-B/32 (FP32)',
value: models.imageEmbeddings.CLIP_VIT_BASE_PATCH32.XNNPACK_FP32,
},
];

const DEFAULT_LABELS = [
'a photo of a dog',
'a photo of a cat',
'a landscape photo',
'a photo of food',
'a photo of people',
];

// CLIP text and image embeddings are L2-normalized, so their cosine similarity
// is the dot product.
const dot = (a: Float32Array, b: Float32Array) => {
let s = 0;
for (let i = 0; i < a.length; i++) {
s += a[i]! * b[i]!;
}
return s;
};

function ImageEmbeddingsContent() {
const [selectedImageModel, setSelectedImageModel] = useState<any>(IMAGE_MODEL_OPTIONS[0].value);
const [imageUri, setImageUri] = useState<string | null>(null);
const [labels, setLabels] = useState<string[]>(DEFAULT_LABELS);
const [newLabel, setNewLabel] = useState('');
const [results, setResults] = useState<{ label: string; score: number }[]>([]);
const [latency, setLatency] = useState<number | null>(null);
const [isProcessing, setIsProcessing] = useState(false);
const [error, setError] = useState<string | null>(null);

const insets = useSafeAreaInsets();
const skiaImage = useImage(imageUri, (err) => setError(err.message || String(err)));

// Zero-shot classification pairs a CLIP image encoder with the CLIP text
// encoder and scores the image against each text label by embedding similarity.
const imageModel = useImageEmbedder(selectedImageModel);
const textModel = useTextEmbedder(models.textEmbeddings.CLIP_VIT_BASE_PATCH32_TEXT);

const ready = imageModel.isReady && textModel.isReady;

const pickImage = async () => {
setError(null);
try {
const uri = await getImage(false);
if (!uri) return;
setImageUri(uri);
setResults([]);
setLatency(null);
} catch (e: any) {
setError(e.message || String(e));
}
};

const classify = async () => {
if (!skiaImage || !ready || !imageModel.embed || !textModel.embed) return;
setIsProcessing(true);
setError(null);
try {
const start = Date.now();
const imageEmbedding = await imageModel.embed(skImageToBuffer(skiaImage));
const scored: { label: string; score: number }[] = [];
for (const label of labels) {
const textEmbedding = await textModel.embed(label);
scored.push({ label, score: dot(imageEmbedding, textEmbedding) });
}
scored.sort((a, b) => b.score - a.score);
setLatency(Date.now() - start);
setResults(scored);
} catch (e: any) {
setError(e.message || String(e));
} finally {
setIsProcessing(false);
}
};

const addLabel = () => {
const trimmed = newLabel.trim();
if (!trimmed || labels.includes(trimmed)) return;
setLabels((prev) => [...prev, trimmed]);
setNewLabel('');
setResults([]);
};

const removeLabel = (label: string) => {
setLabels((prev) => prev.filter((l) => l !== label));
setResults((prev) => prev.filter((r) => r.label !== label));
};

const activeError = imageModel.error
? String(imageModel.error)
: textModel.error
? String(textModel.error)
: error;

return (
<ScrollView
style={commonStyles.container}
contentContainerStyle={[commonStyles.contentContainer, { paddingBottom: insets.bottom + 24 }]}
>
<Text style={commonStyles.description}>
Pick an image, then rank text labels by how well CLIP matches them to it (zero-shot
classification).
</Text>

<ModelPicker
label="Image model"
options={IMAGE_MODEL_OPTIONS}
selectedValue={selectedImageModel}
onValueChange={(model) => {
setSelectedImageModel(model);
setResults([]);
setLatency(null);
}}
/>

<ModelStatus
isReady={ready}
downloadProgress={Math.min(imageModel.downloadProgress, textModel.downloadProgress)}
error={activeError}
modelTypeLabel="CLIP models"
/>

<ImageViewport skiaImage={skiaImage} onPressPlaceholder={pickImage} />

<View style={commonStyles.buttonRow}>
<Button title="Pick image" onPress={pickImage} variant="secondary" />
<Button
title="Find best label"
onPress={classify}
disabled={!skiaImage || !ready || isProcessing}
loading={isProcessing}
/>
</View>

<LatencyIndicator latency={latency} />

{results.length > 0 && (
<View style={styles.card}>
<Text style={styles.cardTitle}>Results</Text>
{results.map((r, i) => (
<View key={r.label} style={styles.row}>
<Text style={[styles.rowLabel, i === 0 && styles.topLabel]} numberOfLines={1}>
{i === 0 ? '🥇 ' : ''}
{r.label}
</Text>
<Text style={styles.rowScore}>{r.score.toFixed(3)}</Text>
</View>
))}
</View>
)}

<View style={styles.card}>
<Text style={styles.cardTitle}>Labels</Text>
{labels.map((label) => (
<View key={label} style={styles.row}>
<Text style={styles.rowLabel} numberOfLines={1}>
{label}
</Text>
<TouchableOpacity onPress={() => removeLabel(label)} hitSlop={8}>
<Text style={styles.remove}>✕</Text>
</TouchableOpacity>
</View>
))}
<View style={styles.addRow}>
<TextInput
style={styles.input}
placeholder="Add a label…"
placeholderTextColor="#94A3B8"
value={newLabel}
onChangeText={setNewLabel}
onSubmitEditing={addLabel}
returnKeyType="done"
/>
<Button title="Add" onPress={addLabel} disabled={!newLabel.trim()} variant="secondary" />
</View>
</View>
</ScrollView>
);
}

export default function ImageEmbeddingsScreen() {
return (
<ScreenWrapper>
<ImageEmbeddingsContent />
</ScreenWrapper>
);
}

const styles = StyleSheet.create({
card: {
width: '100%',
backgroundColor: '#fff',
borderRadius: 12,
padding: 16,
borderWidth: 1,
borderColor: '#e9ecef',
marginTop: 16,
},
cardTitle: {
fontSize: 16,
fontWeight: '600',
color: ColorPalette.strongPrimary,
marginBottom: 8,
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 8,
borderBottomWidth: 1,
borderBottomColor: '#f1f3f5',
},
rowLabel: { fontSize: 14, color: '#334155', flex: 1, marginRight: 8 },
topLabel: { fontWeight: '700', color: ColorPalette.strongPrimary },
rowScore: { fontSize: 13, fontWeight: '600', color: ColorPalette.primary },
remove: { fontSize: 16, color: '#94A3B8', paddingHorizontal: 4 },
addRow: { flexDirection: 'row', alignItems: 'center', gap: 8, marginTop: 12 },
input: {
flex: 1,
backgroundColor: '#f1f3f5',
borderRadius: 10,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 14,
color: '#0F172A',
},
});
3 changes: 3 additions & 0 deletions apps/computer-vision/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export default function Home() {
<TouchableOpacity style={styles.button} onPress={() => router.navigate('classification/')}>
<Text style={styles.buttonText}>Classification</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={() => router.navigate('imageEmbeddings/')}>
<Text style={styles.buttonText}>Image Embeddings</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={() => router.navigate('detection/')}>
<Text style={styles.buttonText}>Object Detection</Text>
</TouchableOpacity>
Expand Down
2 changes: 2 additions & 0 deletions apps/computer-vision/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
"react-native-executorch": {
"features": [
"classification",
"imageEmbeddings",
"textEmbeddings",
"instanceSegmentation",
"keypointDetection",
"objectDetection",
Expand Down
26 changes: 26 additions & 0 deletions apps/computer-vision/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';
import type { SkImage } from '@shopify/react-native-skia';

/**
* Converts a Skia image into the raw RGBA/HWC image buffer that
* react-native-executorch vision tasks accept. Throws if the pixel data cannot
* be read.
* @param image - The Skia image to read pixels from.
* @returns The RGBA/HWC image buffer with its `data`, `width`, `height`,
* `format`, and `layout`.
*/
export const skImageToBuffer = (image: SkImage) => {
const pixels = image.readPixels();
if (!pixels) {
throw new Error('Failed to read pixels from image');
}
if (!(pixels instanceof Uint8Array)) {
throw new Error('Expected Uint8Array from readPixels');
}
return {
data: pixels,
width: image.width(),
height: image.height(),
format: 'rgba' as const,
layout: 'hwc' as const,
};
};

export const getImage = async (
useCamera: boolean,
Expand Down
7 changes: 7 additions & 0 deletions apps/nlp/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export default function Layout() {
title: 'Tokenizer',
}}
/>
<Drawer.Screen
name="text-embeddings/index"
options={{
drawerLabel: 'Text Embeddings',
title: 'Text Embeddings',
}}
/>
</Drawer>
);
}
3 changes: 3 additions & 0 deletions apps/nlp/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export default function Home() {
<TouchableOpacity style={styles.button} onPress={() => router.navigate('tokenizer/')}>
<Text style={styles.buttonText}>Tokenizer</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={() => router.navigate('text-embeddings/')}>
<Text style={styles.buttonText}>Text Embeddings</Text>
</TouchableOpacity>
</View>
</View>
);
Expand Down
Loading