Artificial Intelligence
Review, burst assessments, semantic search and the boundaries between RawCull and its model providers.
Artificial intelligence in RawCull
Use Review to inspect selected or tagged photos. Use the burst list to assess ranked pairs across a catalog. Both workflows run inference locally. Each exposes different evidence and stores its results for a different lifetime.
| Task | Input and result | Guide |
|---|
| Inspect focus, describe a photo or run all Review stages | One to eight selected or tagged images. Review saves a run record and can retain the exact inputs behind a finding. | Review presets and findings |
| Compare a burst’s top candidates across the catalog | The recommended and distinct alternate from each eligible ranked group. AI Assessments displays session results. | Burst groups |
| Request an assessment from a desktop AI client | An authorized MCP source job. The consumer reads structured findings under the shared job’s consent and retention rules. | RawCull MCP |
| Find similar frames or search by description | Vision or CLIP image artifacts support visual similarity. Text queries require compatible CLIP embeddings. | CLIP indexing and search |
Model and application boundaries
SAM 3 produces candidate masks for prompted subjects. Review uses registered masks for subject-detail measurements. DataComp CLIP encodes images and text for comparison. Qwen3-VL supplies whole-photo descriptions, crop observations and report text where the preset calls for them. Qwen also supplies the structured findings for burst and MCP assessments. A stored model finding is advisory. Tagging, rating and marking a burst reviewed require an explicit action.
PhotoAIKit owns provider contracts, model validation, inference backends and reusable indexing workflows. RawCull owns the catalog, file access, model activation, run budgets, evidence presentation and culling decisions. PhotoAnalysisKit owns sharpness and Vision measurement facilities. Its Vision queue is also used by the app’s PhotoAIKit feature-print backend.
The earlier AI Analysis tabs appeared in development builds. Their source-level replacement and rationale are recorded in the AI feature decision.
1 - RawCull AI models
Download and prepare the three AI model packs
Recipe scope (16 October 2026): Preserve the dated source/exporter pins
below when reproducing the original packs. The current RawCull lockfile uses
PhotoAIKit 3.1.0 (26647c62d9933968d92bd00b162290cdd7c78fee) and coreai-models
1.0.0 (5de95c6cd29e5e390fb36d87e13b2396668f7974). An older recipe pin is
not the current app dependency. Compare exporter options and model provenance
before building new candidates. This documentation review did not run model
conversion, download packs or qualify their output.
This is a terminal workbook for rebuilding RawCull’s DataComp CLIP, Meta
SAM 3, and Qwen3-VL-2B-Instruct model packs from source and finishing with
three Apple Managed Background Assets .aar files. It was assembled on
September 26, 2026 from the local PhotoAIKit exporters, the RawCull release
runbook, and the existing layout in /Users/thomas/ModelAssets/Release.
Run each numbered block in zsh and inspect the indicated output before the
next block. The workbook builds in a fresh directory below
/Users/thomas/ModelAssets; it does not overwrite the three existing
Release/Output/*.aar files. Conversion is CPU and memory intensive and the
source downloads are several gigabytes. Keep ample free space for source
weights, intermediate models, three converted bundles, and three archives.
These commands produce local release candidates, not App Store approval.
After packaging, compare the new hashes with the application catalog and follow
the publishing runbook
to update RawCull, upload the packs, and test a signed TestFlight build. A fresh conversion may produce different archive
bytes even when the same source model was used.
0. What will be produced
| Model | Permanent pack ID | Selected installed model path | Output archive |
|---|
| DataComp CLIP | rawcull-clip-datacomp | Models/CLIP-DataComp | clip-datacomp.aar |
| Meta SAM 3 | rawcull-sam3 | Models/SAM3 | sam3.aar |
| Qwen3-VL-2B-Instruct | rawcull-qwen3-vl-2b | Models/Qwen/qwen3_vl_2b | qwen3-vl-2b.aar |
The starting evidence is the RawCull repository at
/Users/thomas/GitHub/RawCull/RawCull, its sibling
/Users/thomas/GitHub/RawCull/PhotoAIKit, and the notices in
RawCull/ModelAssets/Notices. The old archive sizes and SHA-256 values in the
application catalog describe the September 17, 2026 artifacts, not expected
values for this rebuild. OpenAI CLIP and EfficientSAM are outside this
three-pack release.
Install Xcode 27 with the Core AI and Background Assets tools and select it in
Xcode Settings or with xcode-select. Install git and uv if needed. The
commands below merely check the selected tools:
set -e
set -o pipefail
RAWCULL_REPO='/Users/thomas/GitHub/RawCull/RawCull'
PHOTOAIKIT_REPO='/Users/thomas/GitHub/RawCull/PhotoAIKit'
MODEL_ASSETS='/Users/thomas/ModelAssets'
test -d "$RAWCULL_REPO/.git"
test -d "$PHOTOAIKIT_REPO/.git"
test -d "$MODEL_ASSETS"
command -v uv
command -v git
command -v python3
xcode-select -p
xcodebuild -version
xcrun ba-package --version
If uv is missing and Homebrew is available, install it with brew install uv, then rerun the checks. Record the exact tool versions with the eventual
archive hashes. At the time this workbook was written the local Mac selected
Xcode 27.0 (27A266a) and ba-package 2.0; a later toolchain can produce
different output. The PhotoAIKit exporter scripts declare their Python
dependencies in their own # /// script blocks, so uv run creates the
appropriate isolated environments automatically. Do not combine the CLIP and
SAM dependency sets by hand: their transformers requirements differ.
2. Start a clean build directory
Paste this block into the same Terminal window that will run later blocks. If
you open a new window, rerun the variable definitions in this block and set
BUILD_ROOT to the directory printed by echo.
set -e
set -o pipefail
RAWCULL_REPO='/Users/thomas/GitHub/RawCull/RawCull'
PHOTOAIKIT_REPO='/Users/thomas/GitHub/RawCull/PhotoAIKit'
MODEL_ASSETS='/Users/thomas/ModelAssets'
BUILD_ROOT="$(mktemp -d "$MODEL_ASSETS/Build-2026-09-26.XXXXXX")"
HF_HOME="$BUILD_ROOT/HuggingFace"
HF_HUB_CACHE="$HF_HOME/hub"
export HF_HOME HF_HUB_CACHE
mkdir -p "$BUILD_ROOT/Release/Models/Qwen" \
"$BUILD_ROOT/Release/Notices" \
"$BUILD_ROOT/Release/Packaging" \
"$BUILD_ROOT/Release/Output" \
"$BUILD_ROOT/Release/Evidence" \
"$BUILD_ROOT/Tools"
echo "BUILD_ROOT=$BUILD_ROOT"
df -h "$MODEL_ASSETS"
This layout isolates the Hugging Face cache and the new release candidates.
Never run rm -rf against the existing ModelAssets/Release tree to make room.
For a later run, change the date in the mktemp template or leave it: the
random suffix still creates a separate directory.
3. Freeze source and exporter revisions
The model revisions recorded in the existing RawCull catalog are:
CLIP_REV='4afec35ffe57a943d569ff7ee888061830164da8'
SAM_REV='3c879f39826c281e95690f02c7821c4de09afae7'
QWEN_REV='78448d793a7eb2f7a987a1da76d464384aa1becd'
CLIP_TOKENIZER_REV='3d74acf9a28c67741b2f4f2ea7635f0aaf6f0268'
COREAI_MODELS_REV='475c585fdb0fe82a83c8f777f259e9414bd44c98'
COREAI_MODELS_REV is the revision pinned by the local PhotoAIKit package in
the September 2026 RawCull work. These revision labels are a starting recipe.
The old DataComp and Qwen provenance explicitly does not prove which exact
weight bytes their exporters consumed. This rebuild records the actual source
inventory so its evidence is stronger.
First save the repository states. If either repository has local changes to
the exporter, review them before proceeding:
git -C "$RAWCULL_REPO" rev-parse HEAD | tee "$BUILD_ROOT/Release/Evidence/rawcull-commit.txt"
git -C "$PHOTOAIKIT_REPO" rev-parse HEAD | tee "$BUILD_ROOT/Release/Evidence/photoaikit-commit.txt"
git -C "$RAWCULL_REPO" status --short
git -C "$PHOTOAIKIT_REPO" status --short
shasum -a 256 "$PHOTOAIKIT_REPO/Tools/export_clip.py" \
"$PHOTOAIKIT_REPO/Tools/export_sam3.py" \
"$PHOTOAIKIT_REPO/Tools/select_sam3_asset.py" \
| tee "$BUILD_ROOT/Release/Evidence/photoaikit-exporters-sha256.txt"
Get Apple’s converter at the selected revision in the build directory. A
normal git clone also preserves its licence and Python project configuration.
If the pinned revision is unavailable, stop and choose a reviewed revision;
do not silently use the current main branch.
git clone https://github.com/apple/coreai-models.git "$BUILD_ROOT/Tools/coreai-models"
git -C "$BUILD_ROOT/Tools/coreai-models" checkout --detach "$COREAI_MODELS_REV"
git -C "$BUILD_ROOT/Tools/coreai-models" rev-parse HEAD \
| tee "$BUILD_ROOT/Release/Evidence/coreai-models-commit.txt"
4. Download immutable Hugging Face snapshots
SAM 3 is gated: sign in to Hugging Face in a browser, request/receive access to
facebook/sam3, accept its terms, and authenticate the terminal with
uvx --from huggingface-hub hf auth login. Do not paste your access token into
this workbook or a shell command. Qwen and DataComp are public, but checking
their model cards and current redistribution terms is still part of release
review. These downloads use Hugging Face’s CLI.
uvx --from huggingface-hub hf auth whoami
uvx --from huggingface-hub hf download \
laion/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K \
--revision "$CLIP_REV" \
--local-dir "$BUILD_ROOT/Source/CLIP-DataComp"
uvx --from huggingface-hub hf download facebook/sam3 \
--revision "$SAM_REV" \
--local-dir "$BUILD_ROOT/Source/SAM3"
uvx --from huggingface-hub hf download Qwen/Qwen3-VL-2B-Instruct \
--revision "$QWEN_REV" \
--local-dir "$BUILD_ROOT/Source/Qwen"
The exporters do not all take a --revision or --source-dir flag. To make
their ordinary model-ID lookups use the selected snapshots, populate the
isolated Hugging Face cache at the same revisions and bind its main refs to
those revisions. This is explicit, local to BUILD_ROOT, and leaves your
ordinary Hugging Face cache alone. The CLIP exporter also obtains the OpenAI
CLIP tokenizer, so cache it separately.
uvx --from huggingface-hub hf download \
laion/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K \
--revision "$CLIP_REV"
uvx --from huggingface-hub hf download facebook/sam3 --revision "$SAM_REV"
uvx --from huggingface-hub hf download Qwen/Qwen3-VL-2B-Instruct \
--revision "$QWEN_REV"
uvx --from huggingface-hub hf download openai/clip-vit-base-patch32 \
--revision "$CLIP_TOKENIZER_REV"
mkdir -p "$HF_HUB_CACHE/models--laion--CLIP-ViT-B-32-256x256-DataComp-s34B-b86K/refs" \
"$HF_HUB_CACHE/models--facebook--sam3/refs" \
"$HF_HUB_CACHE/models--Qwen--Qwen3-VL-2B-Instruct/refs" \
"$HF_HUB_CACHE/models--openai--clip-vit-base-patch32/refs"
printf '%s' "$CLIP_REV" > "$HF_HUB_CACHE/models--laion--CLIP-ViT-B-32-256x256-DataComp-s34B-b86K/refs/main"
printf '%s' "$SAM_REV" > "$HF_HUB_CACHE/models--facebook--sam3/refs/main"
printf '%s' "$QWEN_REV" > "$HF_HUB_CACHE/models--Qwen--Qwen3-VL-2B-Instruct/refs/main"
printf '%s' "$CLIP_TOKENIZER_REV" > "$HF_HUB_CACHE/models--openai--clip-vit-base-patch32/refs/main"
The first --local-dir downloads are the inspectable evidence copies; the
second downloads populate the cache actually used by the model-ID loaders.
Record source hashes, including every Qwen weight shard:
find "$BUILD_ROOT/Source" -type f ! -name '.DS_Store' -print0 \
| xargs -0 shasum -a 256 \
| sort > "$BUILD_ROOT/Release/Evidence/source-files-sha256.txt"
rg 'safetensors|tokenizer.json|LICENSE' \
"$BUILD_ROOT/Release/Evidence/source-files-sha256.txt" | head -80
Check that the expected source files exist before converting:
test -f "$BUILD_ROOT/Source/SAM3/model.safetensors"
test -f "$BUILD_ROOT/Source/Qwen/config.json"
find "$BUILD_ROOT/Source/Qwen" -maxdepth 1 -name '*.safetensors' -print
find "$BUILD_ROOT/Source/CLIP-DataComp" -maxdepth 1 -type f -print
DataComp binding limitation: open_clip.create_model_and_transforms uses
the datacomp_s34b_b86k preset and may resolve its checkpoint through an
OpenCLIP configuration rather than the checked-out LAION directory. Run it
with the isolated cache and inspect the export log and cache entries. Do not
claim that the LAION file was consumed solely because it was downloaded. If
the resolved source differs, capture that actual source file, revision and
SHA-256, or adapt the exporter to accept an explicit local weight path before
release.
5. Convert DataComp CLIP
The PhotoAIKit exporter creates one two-function .aimodel plus tokenizer and
bundle metadata. Its default DataComp options use ViT-B/32 at 256 px,
datacomp_s34b_b86k, float16, and static shapes. The script itself pins the
Python packages, including coreai-core==1.0.0b2 and
coreai-torch==0.4.1.
cd "$PHOTOAIKIT_REPO"
export HF_HUB_OFFLINE=1
uv run Tools/export_clip.py \
--model openclip-datacomp \
--architecture ViT-B-32-256 \
--pretrained datacomp_s34b_b86k \
--dtype float16 \
--output-dir "$BUILD_ROOT/Release/Models" \
--bundle-name CLIP-DataComp \
2>&1 | tee "$BUILD_ROOT/Release/Evidence/clip-export.log"
The exporter checks parity between the OpenCLIP tokenizer IDs and the saved
PhotoAIKit tokenizer. Stop if that check fails. HF_HUB_OFFLINE=1 intentionally
prevents a network fallback to an unpinned source. If OpenCLIP needs a different
checkpoint repository, find its actual configured repository, pin and download
it, then rerun this block in a new build directory. Do not use --overwrite
until you have saved and reviewed the first result.
test -f "$BUILD_ROOT/Release/Models/CLIP-DataComp/metadata.json"
test -f "$BUILD_ROOT/Release/Models/CLIP-DataComp/tokenizer/tokenizer.json"
test -f "$BUILD_ROOT/Release/Models/CLIP-DataComp/ViT-B-32-256-datacomp_s34b_b86k_float16_static.aimodel/main.mlirb"
cat "$BUILD_ROOT/Release/Models/CLIP-DataComp/metadata.json"
The SAM exporter downloads the gated checkpoint by model ID, exports a source
asset and an optimized runtime asset, and writes tokenizer and metadata. Select
the optimized sam3_float16.aimodel so the package contains the runtime asset
only. The selector refreshes the bundle fingerprint metadata.
cd "$PHOTOAIKIT_REPO"
export HF_HUB_OFFLINE=1
uv run Tools/export_sam3.py \
--model facebook/sam3 \
--dtype float16 \
--output-dir "$BUILD_ROOT/Release/Models" \
--bundle-name SAM3 \
2>&1 | tee "$BUILD_ROOT/Release/Evidence/sam3-export.log"
python3 Tools/select_sam3_asset.py sam3_float16.aimodel \
--bundle-dir "$BUILD_ROOT/Release/Models/SAM3"
Inspect the result. The package selector below includes only the optimized
asset, tokenizer and metadata; it does not include any remaining
*_source.aimodel directory.
test -f "$BUILD_ROOT/Release/Models/SAM3/metadata.json"
test -f "$BUILD_ROOT/Release/Models/SAM3/tokenizer/tokenizer.json"
test -f "$BUILD_ROOT/Release/Models/SAM3/sam3_float16.aimodel/main.mlirb"
cat "$BUILD_ROOT/Release/Models/SAM3/metadata.json"
7. Convert Qwen3-VL-2B-Instruct
Apple’s VLM exporter
creates the text decoder, embedding lookup, vision encoder, tokenizer, and
metadata.json in a qwen3_vl_2b directory. Use the full model: do not set
--num-layers or --skip-vision. The existing RawCull bundle records a 4096
token context. The exporter has no --revision option, so the isolated cache
and offline mode from section 4 matter here. Its output directory is the
parent of qwen3_vl_2b.
cd "$BUILD_ROOT/Tools/coreai-models"
export HF_HUB_OFFLINE=1
uv run coreai.vlm.export --list-models
uv run coreai.vlm.export qwen3-vl \
--max-context-length 4096 \
--compression none \
--output-dir "$BUILD_ROOT/Release/Models/Qwen" \
2>&1 | tee "$BUILD_ROOT/Release/Evidence/qwen-export.log"
If the pinned converter revision does not offer qwen3-vl or one of these
options, stop and inspect that revision’s --help; record and review any
converter revision change. Qwen export can take a long time and use substantial
memory. A process killed by macOS needs a fresh build directory or a carefully
inspected incomplete-output cleanup before retrying.
QWEN_BUNDLE="$BUILD_ROOT/Release/Models/Qwen/qwen3_vl_2b"
test -f "$QWEN_BUNDLE/metadata.json"
test -f "$QWEN_BUNDLE/tokenizer/tokenizer.json"
test -f "$QWEN_BUNDLE/qwen3_vl_2b.aimodel/main.mlirb"
test -f "$QWEN_BUNDLE/embed.aimodel/main.mlirb"
test -f "$QWEN_BUNDLE/vision.aimodel/main.mlirb"
python3 -m json.tool "$QWEN_BUNDLE/metadata.json"
Check that the metadata still names Qwen/Qwen3-VL-2B-Instruct, the three
assets, 448 px vision input, and 4096 context. This is a format check, not an
inference test. RawCull’s Qwen provider must also load and run the bundle.
8. Stage licences, notices and build provenance
Copy the reviewed notice catalog from RawCull. These files include the complete
model, tokenizer, and Apple conversion-recipe notices used by the existing
release. Review their terms and dates against the newly downloaded sources
before redistribution. SAM 3’s licence acceptance is required in RawCull.
for name in CLIP-DataComp SAM3 Qwen; do
ditto "$RAWCULL_REPO/ModelAssets/Notices/$name" \
"$BUILD_ROOT/Release/Notices/$name"
done
find "$BUILD_ROOT/Release/Notices" -type f -maxdepth 2 -print | sort
Those checked-in NOTICE.md files describe earlier published versions. Mark
the staging copies as new candidates without changing their licence text:
python3 - "$BUILD_ROOT" <<'PY'
from pathlib import Path
import sys
base = Path(sys.argv[1]) / 'Release/Notices'
replacements = {
'CLIP-DataComp': (
'RawCull publishes this pack in the v2 model release. The release catalog\n'
'records its download size and version, while the release host records the\n'
'archive checksum. This notice catalog records the upstream reference revision,\n'
'runtime fingerprint, and complete accompanying licence notices.',
'This converted bundle is a new local release candidate. Its final archive\n'
'size, SHA-256, Apple-assigned version, and review status must be recorded\n'
'after packaging and upload.'),
'SAM3': (
'The Apple-hosted asset pack is enabled for download at the project owner\'s\n'
'direction. Its archive byte size and SHA-256 are recorded in the external\n'
'release evidence after packaging, while the host-correct in-pack release record\n'
'is in `PROVENANCE.json`. This release decision does not claim an independent\n'
'legal review. Verified licence acceptance remains required.',
'This converted bundle is a new local release candidate. Record its archive\n'
'size, SHA-256, Apple-assigned version, and review status after packaging\n'
'and upload. Verified SAM licence acceptance remains required.'),
'Qwen': (
'RawCull publishes this pack in the v3 model release. The release catalog\n'
'records its download size and version, while the release host records the\n'
'archive checksum.',
'This converted bundle is a new local release candidate. Record its final\n'
'archive size, SHA-256, Apple-assigned version, and review status after\n'
'packaging and upload.'),
}
for name, (old, new) in replacements.items():
path = base / name / 'NOTICE.md'
content = path.read_text()
if content.count(old) != 1:
raise RuntimeError(f'Expected release paragraph not found: {path}')
path.write_text(content.replace(old, new))
PY
The copied PROVENANCE.json files describe the old release. Replace only
the staging copies with a clearly identified record of this build. The script
below preserves the licence inventory, writes the actual converted-component
hashes, and points to the source inventory. It intentionally has no final .aar
hash because that hash cannot be embedded inside its own archive.
python3 - "$BUILD_ROOT" "$CLIP_REV" "$SAM_REV" "$QWEN_REV" <<'PY'
import datetime, hashlib, json, pathlib, sys
root = pathlib.Path(sys.argv[1])
revisions = dict(zip(('CLIP-DataComp', 'SAM3', 'Qwen'), sys.argv[2:]))
models = {
'CLIP-DataComp': root / 'Release/Models/CLIP-DataComp',
'SAM3': root / 'Release/Models/SAM3',
'Qwen': root / 'Release/Models/Qwen/qwen3_vl_2b',
}
for name, model_dir in models.items():
notice_dir = root / 'Release/Notices' / name
old = json.loads((notice_dir / 'PROVENANCE.json').read_text())
components = {}
for path in sorted(model_dir.rglob('main.mlirb')):
digest = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b''):
digest.update(chunk)
components[str(path.relative_to(model_dir))] = digest.hexdigest()
record = {
'catalog_version': 2,
'release_status': 'candidate',
'release': {
'hosting': 'apple',
'app_bundle_id': 'no.blogspot.RawCull',
'asset_pack_id': {
'CLIP-DataComp': 'rawcull-clip-datacomp',
'SAM3': 'rawcull-sam3',
'Qwen': 'rawcull-qwen3-vl-2b',
}[name],
'packaging_date': datetime.date.today().isoformat(),
'processing_status': 'not-uploaded',
'review_state': 'not-submitted',
},
'model': {
'bundle': old.get('model', {}).get('bundle', name),
'converted_main_mlirb_sha256': components,
},
'upstream': {
'project': old.get('upstream', {}).get('project'),
'selected_revision': revisions[name],
'source_inventory': 'Release/Evidence/source-files-sha256.txt',
'exporter_binding_note': 'Verify exporter log and isolated cache before claiming exact source binding.',
},
'conversion': {
'photoaikit_commit_file': 'Release/Evidence/photoaikit-commit.txt',
'coreai_models_commit_file': 'Release/Evidence/coreai-models-commit.txt',
},
'licences': old.get('licences', []),
}
(notice_dir / 'PROVENANCE.json').write_text(json.dumps(record, indent=2) + '\n')
PY
The staging provenance format is release-candidate evidence; it is not a
drop-in replacement for RawCull’s checked-in PROVENANCE.json. After packaging,
update the repository record using its full validated schema and the final
archive hash, size, App Store Connect pack version, and processing state.
9. Create the three packaging manifests
These selector paths are relative to the current directory used by
ba-package, which must be BUILD_ROOT/Release. Keep the permanent IDs and
installed paths identical to RawCull’s catalog.
cat > "$BUILD_ROOT/Release/Packaging/clip-datacomp.json" <<'JSON'
{
"assetPackID": "rawcull-clip-datacomp",
"downloadPolicy": { "onDemand": {} },
"fileSelectors": [
{ "file": "Models/CLIP-DataComp/metadata.json" },
{ "directory": "Models/CLIP-DataComp/tokenizer" },
{ "directory": "Models/CLIP-DataComp/ViT-B-32-256-datacomp_s34b_b86k_float16_static.aimodel" },
{ "directory": "Notices/CLIP-DataComp" }
],
"platforms": ["macOS"]
}
JSON
cat > "$BUILD_ROOT/Release/Packaging/sam3.json" <<'JSON'
{
"assetPackID": "rawcull-sam3",
"downloadPolicy": { "onDemand": {} },
"fileSelectors": [
{ "file": "Models/SAM3/metadata.json" },
{ "directory": "Models/SAM3/tokenizer" },
{ "directory": "Models/SAM3/sam3_float16.aimodel" },
{ "directory": "Notices/SAM3" }
],
"platforms": ["macOS"]
}
JSON
cat > "$BUILD_ROOT/Release/Packaging/qwen3-vl-2b.json" <<'JSON'
{
"assetPackID": "rawcull-qwen3-vl-2b",
"downloadPolicy": { "onDemand": {} },
"fileSelectors": [
{ "file": "Models/Qwen/qwen3_vl_2b/metadata.json" },
{ "directory": "Models/Qwen/qwen3_vl_2b/tokenizer" },
{ "directory": "Models/Qwen/qwen3_vl_2b/embed.aimodel" },
{ "directory": "Models/Qwen/qwen3_vl_2b/qwen3_vl_2b.aimodel" },
{ "directory": "Models/Qwen/qwen3_vl_2b/vision.aimodel" },
{ "directory": "Notices/Qwen" }
],
"platforms": ["macOS"]
}
JSON
for slug in clip-datacomp sam3 qwen3-vl-2b; do
python3 -m json.tool "$BUILD_ROOT/Release/Packaging/$slug.json" >/dev/null
done
.DS_Store files are present in the older ModelAssets/Release directories;
the new candidate should not include them. Do not delete anything from the old
release. Check the fresh selected directories and resolve any unexpected
symlink or secret before packaging.
cd "$BUILD_ROOT/Release"
find Models/CLIP-DataComp Models/SAM3 Models/Qwen/qwen3_vl_2b \
Notices/CLIP-DataComp Notices/SAM3 Notices/Qwen \
\( -name '.DS_Store' -o -type l \) -print
find Models/CLIP-DataComp Models/SAM3 Models/Qwen/qwen3_vl_2b \
Notices/CLIP-DataComp Notices/SAM3 Notices/Qwen \
-type f -print0 | xargs -0 shasum -a 256 | sort \
> Evidence/selected-inputs-sha256.txt
for slug in clip-datacomp sam3 qwen3-vl-2b; do
xcrun ba-package evaluate "Packaging/$slug.json" \
| tee "Evidence/$slug-evaluate.txt"
done
Read all three Evidence/*-evaluate.txt files. Each list should contain only
its model bundle, tokenizer, metadata, and matching notice directory. The
Qwen pack needs all three .aimodel directories. No source weight files,
download cache, old archive, or other model should be selected. If the
evaluation output is wrong, fix the manifest and rerun evaluation and the
input inventory before packaging.
11. Build the three .aar files
ba-package creates Background Assets archives; .aar is not a ZIP file.
Run it from BUILD_ROOT/Release so the relative file selectors resolve.
cd "$BUILD_ROOT/Release"
xcrun ba-package package Packaging/clip-datacomp.json \
--output-path Output/clip-datacomp.aar --verbose \
2>&1 | tee Evidence/clip-datacomp-package.log
xcrun ba-package package Packaging/sam3.json \
--output-path Output/sam3.aar --verbose \
2>&1 | tee Evidence/sam3-package.log
xcrun ba-package package Packaging/qwen3-vl-2b.json \
--output-path Output/qwen3-vl-2b.aar --verbose \
2>&1 | tee Evidence/qwen3-vl-2b-package.log
Do not edit an archive after this point. Any changed model, metadata, notice,
or manifest requires another ba-package package run and a new hash. For the
three existing App Store Connect pack records, a changed archive will become a
new pack version under the same permanent ID.
12. Verify and record the result
cd "$BUILD_ROOT/Release"
for slug in clip-datacomp sam3 qwen3-vl-2b; do
test -s "Output/$slug.aar"
stat -f '%N|%z bytes' "Output/$slug.aar"
shasum -a 256 "Output/$slug.aar"
shasum -a 256 "Packaging/$slug.json"
done | tee Evidence/archive-and-manifest-sha256.txt
find Output -maxdepth 1 -type f -name '*.aar' -print | sort
The last command must print exactly these three paths:
Output/clip-datacomp.aar
Output/qwen3-vl-2b.aar
Output/sam3.aar
Compare the final selected-inputs-sha256.txt with a fresh hash pass to catch
any source mutation while the archives were built:
find Models/CLIP-DataComp Models/SAM3 Models/Qwen/qwen3_vl_2b \
Notices/CLIP-DataComp Notices/SAM3 Notices/Qwen \
-type f -print0 | xargs -0 shasum -a 256 | sort \
> Evidence/selected-inputs-after-sha256.txt
diff -u Evidence/selected-inputs-sha256.txt \
Evidence/selected-inputs-after-sha256.txt
An empty diff and exit status 0 confirm that the selected inputs remained
unchanged during packaging. Record the BUILD_ROOT path, Xcode version,
exporter commits, source hashes, and all three archive hashes with the release
candidate. The files are at:
<BUILD_ROOT>/Release/Output/clip-datacomp.aar
<BUILD_ROOT>/Release/Output/sam3.aar
<BUILD_ROOT>/Release/Output/qwen3-vl-2b.aar
13. Before uploading or calling these release files
- Verify that the DataComp exporter actually consumed the pinned checkpoint;
the downloaded LAION snapshot alone does not prove it. For all three packs,
retain actual source-weight hashes and exporter logs.
- Review the current model licences and all copied notice files. Keep the
correct notice directory inside each
.aar. - Run RawCull’s
make verify-model-provenance, catalog and release-metadata
tests, and release preflight after updating its manifest template,
Swift catalog, and checked-in provenance to the new archive values. Never
leave the old archive SHA-256 in the app catalog for new .aar files. - If uploading, use the existing
rawcull-clip-datacomp, rawcull-sam3, and
rawcull-qwen3-vl-2b App Store Connect records. Follow
RawCull/Docs/newmodels.md
for xcrun altool, API-key handling, processing checks, and TestFlight
verification. The AppStore build must use Apple hosting and the matching
App Group. A successful local .aar build does not test runtime inference.
If a step fails
| Symptom | Check |
|---|
401/403 downloading SAM 3 | Hugging Face approval and hf auth whoami; accept the gated model terms. |
| Offline source missing | Check the isolated HF_HUB_CACHE and the model’s refs/main; download the exact revision before re-exporting. |
| CLIP tokenizer parity failure | Do not package; inspect the tokenizer source and OpenCLIP configuration. |
| SAM export leaves source asset | Package only the optimized asset selected by select_sam3_asset.py. |
Qwen bundle lacks vision.aimodel | Rebuild with a converter that supports Qwen VLM and without --skip-vision. |
ba-package evaluate lists extra files | Correct its fileSelectors; evaluate again before packaging. |
| Archive hash differs from the old release | Expected for a new conversion; update catalog and provenance before upload. |
The source commands and pack layout come from PhotoAIKit’s export tools,
Apple’s Core AI model recipes,
Apple’s managed pack documentation,
and the RawCull release runbook linked above. Verify the exact checkout used
for a release: repository main branches and tool versions can change.
October 13: verify an installed candidate before interpreting success
The conversion workbook above preserves its September build procedure. The
October application snapshot was the version-3.3.0 working tree with PhotoAIKit
7f9adfcd69661c6bae4a640c16a4056dfc7393df and Core AI models
1953c4f90ba0214c1abc7bebcb9be5107e329a46. Recheck exporter command-line options
at the revisions actually used for a new conversion; application dependency
pins do not silently update an already exported model or its provenance.
There are independent gates:
- Archive integrity: recorded bytes, SHA-256, selected files and notices.
- Installation/provider admission: required assets, metadata and modality.
- Inference: finite vectors, usable masks, or nonempty generated responses.
- Contract acceptance: IDs, enums, evidence ownership and response limits.
- Visual qualification: annotations, source comparisons and useful judgments.
A successful archive or model load does not imply the later gates passed.
The app’s catalog hash describes a specific release archive, not every future
conversion of the same upstream weights.
For build 466, use make combinedinputstest for installed-model input contracts or make combinedselectiontest for the six-file selection probe. The October tab runner was retired with AI Analysis. Keep request images and model responses private when collecting photographic evidence. Verify Apple-hosted installation separately on a TestFlight or App Store build. Makefile
Relationship to the current application
This is a pinned model-preparation recipe. Its exporter revisions, source-weight
snapshots and historical tool versions are retained deliberately; the October 22
application review did not rebuild or publish model packs. Do not substitute a
new source revision into the commands merely because the app version changed.
Current download/installation UI ownership is described in
AI Runtime, and evaluation entry points in
the RawCull test plans (RawCull.xctestplan, ReleaseObjects.xctestplan, ReleaseSharpness.xctestplan). Earlier links to
RawCull/Docs/newmodels.md open historical commits because that report has been
removed from the current application tree.
To trace an installed bundle from its resolved directory into a provider and an
inference request, see Full Review execution.
2 - Full Review Execution
A source-level trace from the Full preset through installed model URLs, prompts, local inference, and saved evidence.
Trace a Full Review from SwiftUI to saved evidence
Open the Review workspace, select Full in the preset control, then click Review to start. This walkthrough follows RawCull 3.5.0 build 468 and its resolved PhotoAIKit 3.1.0 and Core AI Models 1.0.0 dependencies. The links point to the source revisions used for the trace. Build 466 has the same Review implementation and package pins. Application lockfile
1. Follow the installed model URLs into PhotoAIKit
Settings activates the models before Review runs. The model download service asks Background Assets for each installed bundle directory using AssetPackManager.shared.url(for: FilePath(descriptor.assetPackModelPath)) and checks that the returned URL names an existing directory. The production catalog paths are Models/Qwen/qwen3_vl_2b, Models/SAM3 and Models/CLIP-DataComp. These are asset-pack-relative paths. At a breakpoint, inspect the returned file URL to see the location on that Mac. The download coordinator collects installed locations into a snapshot, which RawCullAISettingsModel applies to RawCullAIModelRuntime. Download catalog · Download service · Settings model
| Model | RawCull handoff | PhotoAIKit receives and keeps |
|---|
| Qwen | applyManagedModelLocations calls the Qwen actor’s validate(url:) with the installed directory. The actor standardizes it and calls CoreAIQwenProvider.factory.capability(in: [standardizedURL]), then makeProvider(from:). | CoreAIQwenProvider(modelBundleURL:) validates the directory and reads metadata.json. It checks Qwen tokenizer/source identifiers, positive vocabulary and context sizes and, for a VLM, vision metadata plus the embedding and vision asset files. RawCull requires vision modality. The provider retains the bundle URL. On first inference, makeVisionLanguageModel() passes it to CoreAIVisionLanguageModel(resourcesAt:). |
| SAM 3 | The model runtime updates its SAM resource manager’s candidate URL. load() asks CoreAISAM3Provider.factory to resolve and construct a provider. | The provider records the identity of the validated bundle. On first inference, loadModel() opens the tokenizer and constructs CoreAISegmentationEngine using the resolved main asset. For a flat exporter tokenizer layout, the provider can stage metadata and tokenizer files in a temporary directory with a symlink to the model asset. |
| CLIP | Separate resource managers validate DataComp and OpenAI candidates with CoreAICLIPProvider.factory. The model runtime keeps validated providers and their resolved locations. | The provider stores the resolved model URL, bundle identity and preprocessing configuration. Its lazy load opens the model functions and tokenizer using the bundle metadata and model descriptors. |
The PhotoAIKit factory boundary is capability(in: [URL]) → ModelResource → makeProvider(from:) → concrete provider. The package resolves metadata, required paths and asset identity from the candidate directories RawCull supplies. RawCull’s SAM and CLIP resource managers can reuse a capability/provider pair while their recursive filesystem snapshot still matches. Qwen validation instead cancels active generation, increments its generation counter and resets the loaded model. Resource manager · Package resource contracts · Qwen provider · SAM provider · CLIP provider
When Review requests a live backend, the factory in RawCullIntelligenceRuntime captures the shared Qwen actor and its available URL, the SAM 3 object-instance service and serialized SAM identity, and the CLIP provider and location. It prefers DataComp, with OpenAI CLIP as the fallback when DataComp is absent. The Review backend uses the captured Qwen and CLIP URLs to check bundle identity. Actual inference uses the configured actor or provider. SAM’s URL is already inside its provider. The current configuration refresh coordinates with Review through the shared lease before replacing model state. Runtime factory · Model runtime · Live backend
2. Follow the Review action to the saved run snapshot
- The toolbar opens the Review workspace.
CombinedReviewWorkspaceView passes either the grid selection (the default) or the tagged images from CatalogController.aiAnalysisFiles(for:) into CombinedReviewView. The thumbnail selection controls which photo is displayed. The input picker controls the files passed to the run. Workspace input - In
CombinedReviewRunBar, the segmented picker binds to feature.preset. Selecting Full writes .full. In CombinedReviewRunActions, the Review action projects the workspace files into ReviewSelectedFile values with catalog ID, photo URL, display name, normalized AF point and ISO, then calls CombinedReviewFeature.analyze. SwiftUI controls - The feature evaluates selection, criteria, source availability and model readiness. The criteria must be nonblank and at most 512 UTF-8 bytes after trimming. The Qwen presets require a Mac with at least 16 GB of unified memory. A new run requests the shared Review lease, constructs the backend and captures the chosen preset, depth, source and retention settings. The worker freezes one to eight files with fingerprints and retains security-scoped access through
ReviewCatalogSession. A user region is captured for a single selected image. Feature admission · File admission backend.models(for: .full) checks Qwen’s 448 × 448 stretch input, 196 image tokens, 4096-token context and exact bundle tree hash. The tree hash combines sorted relative paths and SHA-256 digests of the visible regular files. CLIP admission recognizes two bundle hashes with 224- or 256-pixel geometry. The SAM snapshot records provider identity and the source-normalized mask contract. Full requires Qwen. Missing SAM or unrecognized CLIP can leave individual stages unavailable while the run continues. Model admission · Preset contractReviewRunSnapshot freezes the file and model identities, trimmed criteria, depth, source preference, retention flags, stage versions, pipeline version and 768-token response limit. The feature validates it and saves the initial work manifest before calling execute. Follow manifest.snapshot.id through progress, result and storage breakpoints. Snapshot and worker · Initial manifest
3. Locate the Qwen prompt boundary
RawCull builds a separate instruction for each Qwen stage. CombinedReviewLiveBackend.respond(instruction:image:tokens:) copies the instruction string, CGImage and output limit into a RawCull QwenVisionRequest. Inside QwenInferenceRuntime.respond(to:), the request waits on the generation gate and verifies that the model generation still matches. The first request uses the PhotoAIKit provider to construct the vision-language runtime. Later requests reuse the loaded runtime. The actor creates a fresh Foundation Models session per request and supplies the image first and the instruction second. Live backend · Generation code
let session = LanguageModelSession(model: model)
let response = try await session.respond(
options: GenerationOptions(maximumResponseTokens: request.maximumResponseTokens),
) {
Attachment(request.image)
request.instruction
}
There are two boundaries to inspect. PhotoAIKit’s Qwen provider takes the model directory and constructs the Core AI model. The session takes the request text and pixels and invokes that model locally. Each request has its own prompt and attachment. Earlier stage data reaches later calls only where RawCull explicitly interpolates it into instructions or uses it to choose pixels. After generation, the actor checks cancellation and generation again, trims response.content and rejects an empty response. The stage parser then validates the text against that stage’s schema. Provider constructor · Runtime request and response
Before dispatch, CombinedReviewResponse.admitted checks instruction.utf8.count + imageTokens + outputTokens + 256 <= contextTokens. This conservatively charges one unit per UTF-8 byte and reserves framing space. With the accepted Qwen model and the normal 768-token response limit, the instruction allowance is 2,876 bytes. validatedResponse can append a bounded correction and retry a rejected response with the same image, subject to prompt admission and the repair budget. Inspect the original instruction, the validation issue and the repaired instruction separately. Prompt admission · Stage validation and repair
4. Step through a single photo
execute sorts files by stable review ID, allocates crop slots round robin across the selection, and calls prepare → plan → inspect → finish for each photo. The source, overview, subject identity and report have stable work IDs. Dynamic work IDs describe the concept, subject or region being processed. Execution
Prepare the source and ask Qwen for an overview
prepare opens the frozen photo URL with the chosen source preference and the appearance policy. Inspect source.metadata, source.image and source.overview to distinguish the rendered source from its overview raster, whose default maximum side is 2,048 pixels. The source loader records identity, fidelity and render settings. The Qwen attachment is the overview raster. The admitted model subsequently applies its 448 × 448 stretch preprocessing. Source loader · Prepare
CombinedReviewResponse.overviewInstruction asks for JSON with observations, uncertainty and up to three object concepts. Each concept has query, displayName and reason. The queries should be short singular object noun phrases. This initial discovery instruction is fixed. The user’s Review criteria are used later in CLIP relevance and in the synthesis and comparison goals. The overview parser’s validated concepts are what the next stage sees. Overview instruction and parser
Plan subjects and regions with SAM 3
For each admitted overview concept, plan calls backend.segment(image: source.image, file: file, concept: concept). The live backend constructs a SegmentationConcept and supplies an AIImageSource with the file ID, photo URL and display name to ObjectSegmentationService. The service reads source identity from the URL and bounds the supplied raster to 4,320 pixels on the long side. Review constructs this service with an eight-instance limit and an empty package store list. Planning · Service construction · Package workflow
In CoreAISAM3Provider.infer, the provider tokenizes the concept using the model’s tokenizer context length and calls engine.segment(image:textQuery:parameters:) with .tokens([tokens]). For example, a validated overview concept of bird becomes a tokenized SAM query. The provider decodes instance outputs and the service resizes masks back to the dimensions of the supplied source image. RawCull registers each mask against the appearance source, deduplicates overlapping candidates across concepts and assigns subject priority. With retained subjects, a separate head query can propose a generic child region subject to spatial checks. RawCull then plans bounded crops from retained subjects and the optional user region. Check omissions and the identity work item when a proposed region is missing. SAM inference · Registration and planning
Measure focus, score relevance and inspect crops
- Focus measurement.
inspect may load the technical render of the photo. Where sources are compatible, it maps the registered subject mask to the measurement raster and calls SubjectMaskFocusScorer for subject-local detail evidence. Inspect the recorded source, foreground bounds, mask contract and measurement availability. This work has no generative instruction. Measurement execution · Focus scorer - CLIP relevance. The backend calls
provider.embedding(for: image) and provider.embedding(for: snapshot.criteria) for the overview and eligible crops. The provider preprocesses the image for its configured encoder and runs the image function. It tokenizes the criteria to the text input shape, builds the token batch and any required attention mask, and runs the text function. RawCull checks vector shape and finiteness, computes cosine relevance from the two embeddings, and records the visual embedding and encoder geometry. Inspect the criteria literally as typed, after admission trimming. CLIP returns vectors and relevance rather than prose. CLIP call site · CLIP provider - Qwen crop observation. The attachment is the registered crop. RawCull interpolates the generic target, exact region ID and purpose into the instruction. It requests JSON containing that region ID, four criterion strings or nulls (
composition, exposure, visibility, detail), uncertainty and targetIdentified. The parser validates the ID and target support and can preserve valid criteria while recording abstentions for others. A crop’s detail text must describe resolved texture of the intended target. The run records its provenance and any limitation separately from focus measurements. Crop prompt and result
The depth setting caps crops per photo and across the selection. Standard allows 3 and 16, Deep 8 and 32, and Exhaustive 16 and 64. A slot permits a crop attempt when qualified input exists. The manifest budget also tracks SAM, CLIP, overview, reconciliation, reporting, comparison and repair attempts. Depth contract · Attempt accounting
Reconcile and assemble the per-image report
With both measurements and available crop observations, finish may request reconciliation. The final synthesize call attaches the overview and builds a new instruction from the user’s goal, source information and admitted observation rows. It excludes reconciliation prose from the synthesis inputs. Each row has a short alias such as o1, scope information and supported text. RawCull prioritizes rows and omits optional rows that exceed the context allowance. It computes the eligible row IDs for each criterion before asking Qwen to select one ID or null per criterion. Synthesis implementation · Evidence grounding
The report parser resolves aliases to the original evidence IDs and copies the selected criterion text. Measurements remain available as numeric evidence in the UI. Missing categories and uninspected regions become limitations. If report synthesis fails validation, RawCull saves an evidence-only summary and an incomplete report with no accepted generated claims. This lets the developer distinguish a report-generation failure from the loss of earlier observations. Report fallback and row selection · Response validation
5. Follow the multi-photo branch and saved results
For more than one photo, compare runs after per-image work. It assembles a 2,048 × 2,048 labeled overview board and an instruction referencing evidence from the reviewed photos. The Qwen request attaches that single board. The comparison validates its references and can abstain while leaving per-image reports available. A comparable tie can schedule optional pair boards. Both images must have one candidate subject with the same concept, and their qualified whole-subject crops must match in source policy and fidelity and be within the scale tolerance. Deep allows up to two such pairs and Exhaustive up to four. Comparison calls validate their responses directly through the comparison parser. Comparison execution · Board renderer
perform is the breakpoint for stage transitions, budget consumption, artifact reuse and failure diagnostics. The manifest tracks stage state, dependencies, compatibility and artifact keys. The store writes per-run JSON under runs/ and stage artifacts under stages/ under RawCull/AnalysisArtifacts/CombinedReview in the app’s user Application Support directory. Exact input retention can save the request rasters as PNGs under inputs/ for inspection. Compact retention can still keep masks needed for later processing. Cancel preserves completed work. Resume checks saved compatibility, file and model identities and artifact validity before reusing work. The Review Record window reads the same feature state and links findings to retained inputs and diagnostics. Work execution · Artifact store · Record window
6. Inspect an actual request in Xcode
Start with one photo, Standard depth and Retain exact inputs if you want to compare the UI’s evidence with the request raster after execution. Use a second run with multiple photos to reach the comparison branch.
| Stop here | Inspect |
|---|
RawCullManagedBackgroundAssetsModelDownloadService.modelURL(for:), resource manager load(), or QwenInferenceRuntime.validate(url:) | Installed URL, resolved bundle URL, package capability, constructed provider and model metadata. |
CombinedReviewFeature.analyze and CombinedReviewLiveBackend.models(for:) | Selected preset, frozen file URLs and fingerprints, qwen/sam/clip entries, and bundle hash or capability mismatch. |
CombinedReviewFeature.validatedResponse and QwenInferenceRuntime.generate | Exact instruction, attachment dimensions, response token limit, trimmed raw response and validation or repair outcome. The methods in the execution file extend CombinedReviewFeature. |
ObjectSegmentationService.segment and CoreAISAM3Provider.infer | Concept, image and output sizes, tokenizer output, instance limit, scores and masks. |
CoreAICLIPProvider.embedding(for:) and CombinedReviewLiveBackend.clip | Criteria tokens, preprocessing configuration, embedding dimensions and cosine result. |
CombinedReviewFeature.synthesize and ReviewArtifactStore.saveManifest | Included evidence rows, allowed IDs, stored evidence references, limitations and terminal stage states. |
For a concrete trace, set Review criteria to “judge how clearly the bird stands out.” If the overview returns a valid bird concept, follow it into SAM’s query tokenizer and inspect the returned instance. Follow the resulting subject and region IDs into the crop’s Qwen instruction. At the CLIP breakpoint the original criteria sentence goes into the text encoder. At synthesis, the same sentence is the goal and Qwen chooses among the admitted observation aliases. In the Review Record, trace the selected report claim back through its stored observation ID to the crop input.
The existing CombinedReviewFeatureTests use an injected backend to drive Full, comparison, preset admission and saved-run behavior without installed model packs. For app orchestration debugging, start with ReviewFakeBackend.respond and the test “full preset keeps every stage and saved runs without a preset load as full.” The live breakpoints above cover package inference. Review feature tests
The app also has opt-in Qwen capture via the RAWCULL_AI_CAPTURE_DIR environment variable. Point it to a private directory with no group or other permission bits. For each captured response it writes a PNG of the request raster and JSON with bounded instruction and response text, dimensions, response-token limit and input capabilities. The PNG is taken before backend preprocessing. Compare it with the retained Review input when debugging crop geometry, and inspect the backend separately for encoder tensors. The capture contains photo pixels and request text. Diagnostic capture
For the surrounding lifecycle, see AI Runtime. For the record UI and retention controls, see AI Models in RawCull. For the provider contracts, see PhotoAIKit Architecture.
3 - AI Models in RawCull
Review presets, model requirements, findings, saved evidence, decision controls and CLIP indexing in RawCull.
AI models in RawCull
Open Review from the toolbar to inspect a shortlist. Choose Selected or Tagged, select a preset, then click Review. The selected input must contain one to eight photos. If no grid items are explicitly selected, the focused visible photo can supply the input. Tagged input uses ratings of two or more in the active scope. To assess the top frames across the catalog’s ranked bursts, use Assess All Bursts on the burst list. Burst Groups
Choose a Review preset
| Preset | Required model | What the run produces |
|---|
| Focus check | SAM 3 | Segments the generic subject prompt, registers available masks against the source and measures detail within usable foreground. CLIP can add relevance to the review criteria when available. This preset runs without Qwen. |
| Describe | Qwen3-VL | One whole-photo overview per image. The run finishes after the overview, so expect no region crops or masked measurements. |
| Full | Qwen3-VL | Starts with the overview, uses its concepts for SAM 3 when available, measures registered subjects and inspects crops within the depth budget. Reconciliation and report stages preserve evidence, omissions and conflicts. Multiple images also schedule a selection comparison. Missing optional models limit what the report can establish. |
Describe and Full require at least 16 GB of unified memory. Below 32 GB the app displays a memory advisory. Review starts with Full on eligible machines and switches to Focus check when Qwen presets are disabled for memory. Enter nonblank criteria of at most 512 UTF-8 bytes. Review checks that the chosen preview or RAW-detail source works across the selection. Model availability is checked for the chosen preset when the run starts. ReviewRunContract · CombinedReviewFeature · CombinedReviewLiveBackend
Select Full, then click Review to start. For the call path and model inputs, see Full Review execution.
Read a result
The photo stays in place as you inspect the findings. During a run, the card on the photo shows the current step and progress. Select a finding to see its crop and highlight its region when region evidence exists. Region details shows the subject, crop geometry and provenance. The up and down arrows move between findings and Escape goes back one level. The layer controls below the photo show regions, subject masks and crop geometry.
Open Coverage & limits to see what the run could establish. For example, a mask touching the image edge may represent only part of a subject. A head-shaped region alone cannot establish eye sharpness. A crop omitted because the depth budget ran out has no crop observation. If synthesis fails, read the surviving observations as individual findings. The separate Review Record window follows the selected result and also exposes the technical record, JSON copy action and task history. CombinedReviewView · CombinedReviewInspectorPane · CombinedReviewRecordWindow · CombinedReviewLimitDigest
Follow a finding back to its pixels
A Full run records whether it used an embedded camera preview, a developed RAW or an ordinary raster. The overview is bounded to 2048 pixels on the long side by default. Review records the dimensions and orientation of the source used to cut a crop. It keeps the requested, padded, source and encoder-retained rectangles separately. Inspect exact crop can open the retained input when available. This matters on a small subject near the frame edge, where a source region, the visible foreground and the pixels supplied to the encoder can cover different areas. ReviewImageSource · CombinedReviewInspectorPane
For masked detail, Review loads the technical render, checks alignment against the appearance render, and requires the mask dimensions to match. A valid camera AF point can add evidence about the focus location. If alignment fails or the foreground is unusable, read the resulting limitation before interpreting a focus claim. The detail value depends on the render, with no calibrated sharp/blur threshold. A high CLIP relevance score describes a match to the criteria and cannot qualify an eye as sharp. CombinedReviewExecution
Apply a decision
Reading or reopening a result leaves culling decisions untouched. Tag sets two stars. Untag removes a two-star record. A photo with three to five stars shows a disabled Tagged button so using it cannot erase those stars. Use the rating controls to change them. Mark Reviewed applies to the burst containing the photo and appears when the photo maps to exactly one burst in the active scope.
The decision bar resolves the saved photo against the open, editable catalog and checks its on-disk fingerprint at the time of the action. Scanning, pending shutdown, an unavailable ratings store, duplicate filenames or a changed file can prevent an edit. Ratings use filenames as keys, so duplicate names make the target ambiguous. ReviewDecisionActions · CombinedReviewDecisionBar
Rating keys
With the result active, X rejects, P or 0 marks a keeper, 1 or 2 assigns two stars, 3 or T assigns three, and 4 or 5 assigns the corresponding stars. A text field or other control that owns the keystroke keeps it. The action targets the displayed result after the same live-file checks as the buttons. ImageReviewPolicies · CombinedReviewView
Where the subject outline comes from
Focus check and Full can supply the thumbnail mask badge and the S outline in loupe, zoom and the burst workspace. For the last displayed result matching the standardized photo URL, RawCull prefers an available primary-candidate mask with a retained input key, then the highest-confidence usable mask. Loading the image checks the file fingerprint again. Clearing retained inputs can leave a readable report with no drawable mask. Describe supplies no subject masks. ReviewSubjectMasks · ImageReviewSubjectOutlineLoader
Saved runs and repeatability
The snapshot freezes the preset, files, source preference, criteria, depth, model identities, stage versions and retention choices. The manifest tracks work and dependencies. Focus check starts with source and identity work, Describe with source and overview, and Full adds report work and, for a selection, comparison. Discovered subjects and crop regions add work as the run progresses.
An interrupted run can retain completed evidence. Resume revalidates the saved source fingerprints, model snapshots, pipeline contract and stored artifacts. A historical run without a preset decodes as Full and uses the earlier Full compatibility keys. After relaunch, RawCull restores the latest manifest and task history. The photo picker draws from results held in memory. Resume reconstructs results for a compatible run and reuses valid stage artifacts. If the original photo has changed, the saved task history remains available. When there is no displayed photo result, open Run history & diagnostics in the Review workspace. Clear retained inputs removes stored images. Clear rejected responses removes optional response diagnostics. CombinedReviewFeature+Manifest · CombinedReviewExecution · ReviewRunContract
When resuming, the store checks the stage’s compatibility and that any mask inputs referenced by a segmentation artifact still exist. Evicting a referenced mask makes that stage ineligible for reuse. The historical report can still explain what the earlier run observed. ReviewArtifactStore · ReviewRunContractTests
How CLIP Works in RawCull
CLIP places images and text in a shared vector space. RawCull uses that property
in three ways: image-to-image distance, text-to-image semantic search, and a
small closed-set subject-label pass that helps choose SAM prompts.
Provider construction and identity
PhotoAIKit’s
CoreAICLIPProvider
is an actor implementing image embedding, artifact generation/comparison, text
embedding, and image/text comparison. During initialization it:
- validates the supplied model bundle;
- derives a
ModelIdentity and asset fingerprint; - decodes model-specific preprocessing, tokenizer, function-name,
normalization, and configuration metadata; and
- exposes a
SimilarityBackendDescriptor containing all compatibility-critical
versions.
The descriptor is effectively the type identity of an embedding on disk. It
records backend, model fingerprint, representation, preprocessing,
normalization, and configuration versions. Image artifacts additionally record
vector dimensions, schema version, and a source fingerprint. Consequently,
RawCull does not compare a DataComp vector with an OpenAI vector, reuse an
artifact after preprocessing changes, or silently treat an edited source file
as unchanged.
Image preprocessing and inference
RawCullSimilarityImageDecoder first asks RawParserKitImageLoader for a
bounded thumbnail. If that fails it attempts an ImageIO thumbnail without
requesting a full fallback decode. The resulting CGImage is passed through
the model-specific preprocessing declared by the CLIP bundle. Current metadata
supports either the legacy stretch/bilinear path or shortest-side resize plus
square center crop with bicubic interpolation and configured RGB mean/standard
deviation.
The provider lazily loads Core AI functions and tokenizer resources. The image
function receives the prepared image tensor and, if required by the exported
graph, dummy text inputs. Its output is flattened, checked against the expected
dimension, wrapped in an ImageEmbedding, JSON-encoded, and stored in a
SimilarityArtifact. The backend descriptor records the bundle’s declared
normalization version; image/text comparison later verifies that the image
vector actually has approximately unit magnitude.
Indexing and recovery
RawCullCLIPSimilarityService uses PhotoAIKit’s bounded
SimilarityArtifactIndexer with concurrency limit 1. CLIP inference is kept
serial because the provider is actor-owned and model execution is resource
intensive. There is no per-file or whole-batch Vision substitution during a
CLIP pass.
For a non-finite vector, RawCullRecoveringCLIPArtifactProvider performs a
targeted sequence:
- reject the invalid output;
- retry once with the already-loaded provider;
- construct a fresh provider from the same validated model location;
- verify that the replacement descriptor is exactly the same; and
- retry once with the replacement.
Successful CLIP artifacts from other files are retained. A file that still
fails is reported and remains unindexed; it is not given a Vision artifact that
would make the batch heterogeneous. Decode failures and inference failures are
recorded separately for diagnostics.
Image similarity and burst grouping
For compatible normalized image embeddings, PhotoAIKit returns cosine distance.
SimilarityScoringModel owns the artifact dictionary and computes distances
from an anchor. It can apply a small RawCull-owned subject-label mismatch
penalty, then uses those distances as input to ranking and burst grouping.
This responsibility split is deliberate:
- CLIP defines the vector and mathematical comparison;
- PhotoAIKit defines artifact compatibility and indexing mechanics; and
- RawCull defines catalog admission, grouping thresholds, ordering, progress,
persistence, and culling policy.
Vision remains the runtime fallback when CLIP is disabled or cannot be
validated. Vision and CLIP artifacts are both descriptor-bearing, so switching
backends causes incompatible state to be rejected or rehydrated rather than
misinterpreted.
Semantic search
Semantic search never indexes missing images as a side effect. It operates only
on already-persisted, descriptor-compatible CLIP image artifacts:
flowchart LR
Query["Text query"] --> Tokens["CLIP tokenizer"]
Tokens --> TextModel["CLIP text function"]
TextModel --> TextVector["Validated normalized text vector"]
Images["Compatible cached image artifacts"] --> Compare["Dot product / cosine similarity"]
TextVector --> Compare
Compare --> Sort["Descending score with deterministic tie breaks"]RawCullCLIPSemanticSearchService trims and validates the query, filters image
artifacts by the complete backend descriptor, generates one transient text
embedding, and scores each compatible image. Because both vectors are
normalized, their dot product is cosine similarity. Valid scores lie in
-1...1; they are relative ranking values, not confidence percentages.
Sorting is deterministic: score descending, then original catalog order,
localized filename, and UUID. Individual malformed artifacts become per-file
failures rather than aborting every valid result. Text embeddings are scoped to
one search and are not persisted.
Earlier model evaluations
The September puffin tests exercised the former Objects workflow. All 16 runs produced the expected board IDs, yet visual inspection found swapped bird descriptions and a wrong bird count. Those observations explain why a valid structured response still needs photographic review. The archived guide preserves the fixtures, timings and evidence limits for that workflow. September evaluation
4 - The RawCull AI Runtime
Runtime ownership, model activation, preset admission, inference sharing and Vision scheduling in RawCull.
The RawCull AI runtime
RawCullApplicationState.live() assembles the catalog workspace and long-lived intelligence services. RawCullApp holds the view model and intelligence runtime in SwiftUI state. The main view receives the similarity, semantic search, settings and Review features explicitly. The executable still uses the name CombinedReviewFeature for the feature behind the Review toolbar item. RawCullApp · RawCullIntelligenceRuntime
| Lifetime | Owner | What it owns |
|---|
| App | RawCullAIModelRuntime | Validated CLIP and SAM providers, Vision similarity, subject-mask stores and the Qwen inference actor |
| App | RawCullIntelligenceRuntime | Similarity and semantic search features, Review, settings and downloads, configuration revision, and Review Record navigation |
| App session | BurstBatchAssessment and AIAssessmentNavigation | Qwen batch task, its progress and the burst entries shown in AI Assessments |
| Review run | CombinedReviewFeature | Frozen inputs, model snapshots, task and lease, evidence, manifest and optional retained inputs |
| Displayed Review results | ReviewSubjectMasks | Lookup of a primary or highest-confidence retained mask for a catalog photo. Image loads verify the photo fingerprint. |
From settings to a running Review
- Settings validates installed model locations and publishes a complete configuration. The runtime compares its revision with the last accepted revision. Equal or older revisions leave the active services in place.
- A newer revision with identical descriptors advances the revision alone. Changes to similarity or semantic identity replace those services independently. A segmentation change selects the provider through the model runtime.
- The Review backend factory reads the currently available Qwen URL, the SAM object-instance segmenter, and the CLIP provider and location. The preset determines which model snapshots the run requests. Qwen validation checks encoder capability and bundle identity for a Qwen preset. Focus check can construct a backend with no Qwen URL.
- After admission, the feature holds the shared lease, retains access to selected files, freezes their fingerprints and persists the initial work manifest. Resume uses the original snapshot. A provider or file change can make work incompatible.
- The record window reads the same feature and navigation selection as the main workspace. Opening it does not create another run. The old SAM/CLIP, Qwen and Objects tab controllers have been removed. At startup the model runtime attempts to remove the obsolete Objects mask directory.
RawCullAIModelRuntime · CombinedReviewLiveBackend · CombinedReviewFeature · CombinedReviewRecordWindow
For a debugger walkthrough of Full, including the precise instruction and pixel inputs at each provider boundary, see Full Review execution.
Startup Refresh and Installed-Model Activation
The graph is usable immediately with Vision while disk checks happen later.
The main window attaches the settings refresh to its root view:
.task {
await intelligenceRuntime.settingsModel.refresh()
}
The call path is:
sequenceDiagram
participant View as RawCullMainView
participant Settings as RawCullAISettingsModel
participant Downloads as RawCullAIModelDownloadsModel
participant Models as RawCullAIModelRuntime
participant Resource as Resource-manager actors
participant Runtime as RawCullIntelligenceRuntime
View->>Settings: refresh()
Settings->>Downloads: refresh()
Downloads-->>Settings: applyManagedModelLocations(snapshot)
Settings->>Models: applyManagedModelLocations(snapshot)
Models->>Models: validate or clear Qwen
Models-->>Settings: Qwen status
par model validation
Settings->>Models: refreshCapabilities()
Models->>Resource: load SAM 3 and both CLIP choices
and saved evidence
Settings->>Settings: scan burst caches
end
Models-->>Settings: capabilities
Settings->>Runtime: apply(revisioned configuration)
Runtime-->>Settings: current capabilitiesOne complete location snapshot
applyManagedModelLocations(_:) is the only activation path for a complete set
of installed locations. It gives the current SAM and CLIP URLs to their resource
managers. A missing Qwen URL calls qwenInference.clear(); a present URL is
standardized and validated.
Using a complete snapshot avoids a transient mixture such as “new CLIP, old
SAM, removed Qwen still active.” Every invocation describes one model-install
state.
Generation-gated refresh
Settings increments refreshGeneration before beginning work. The generation
is checked after Qwen validation and after the concurrent capability/evidence
work. A later refresh therefore supersedes an earlier one; the earlier result
cannot publish merely because its disk work finished last.
The defer that clears isScanningSavedBurstData also checks the generation,
so an obsolete refresh cannot hide the current refresh’s progress indicator.
Concurrent capability validation
RawCullAIModelRuntime.refreshCapabilities() starts SAM 3, DataComp CLIP, and
OpenAI CLIP loads with async let. Each resource-manager actor computes a
lightweight recursive metadata snapshot. When unchanged, the previous validated
capability/provider result is reused. When changed, PhotoAIKit validates the
bundle and constructs a provider.
After all three complete, the main-actor runtime atomically replaces its
provider dictionaries and resolved location dictionaries, translates package
statuses into RawCull statuses, builds semantic-search readiness separately,
stores one new capability snapshot, and activates the selected segmentation
provider.
Capability State Is More Than “Loaded”
RawCullAICapabilityStatus distinguishes:
| State | Meaning |
|---|
checking(expectedLocations:) | Validation is pending. |
available(location:) | Bundle validation and provider construction succeeded, or an always-available service such as Vision is ready. |
missing(expectedLocations:) | No candidate bundle was found. |
invalid(location:reason:) | A candidate exists but validation or provider construction failed. |
unavailable(reason:) | The runtime cannot offer the capability for another explicit reason. |
CLIP model availability and semantic-search readiness are separate. A provider
must expose the text/image contracts before semantic search is .ready. Vision
remains a valid similarity service but can never satisfy semantic text search.
Qwen uses an internal QwenModelStatus with not-configured, checking,
available, missing, and invalid states. Settings translates it to the common
capability presentation and retains the validated Qwen status for the Review backend factory.
Resource Managers and Their Cache
RawCullAIModelResourceManager<Provider> is an actor because filesystem
inspection, cryptographic bundle validation, and provider initialization must
not run on the main actor or race with a managed-location change.
The resource cache has two keys:
RawCullAIModelResourceSnapshot, a sorted list of path, file kind, byte
count, modification time, and symlink target; and- the resulting capability, optional provider, and optional provider-init
failure.
setManagedCandidateURL invalidates both when the URL changes. load() also
detects modifications within the same directory. The snapshot only decides
whether validation may be reused. PhotoAIKit’s resolver remains responsible for
metadata, required files, asset extension, fingerprint, and checksum validity.
Bundle validity and provider construction are reported separately. A bundle can
be structurally valid yet fail to initialize its concrete runtime; RawCull maps
that case to .invalid with the provider error so Settings can explain the
actual stage that failed.
Selecting the Similarity Runtime
RawCullAIModelRuntime.similarityService(prefersCLIP:clipModel:) has a strict
selection order:
- If the user disabled CLIP, return the existing Vision service.
- If the selected CLIP provider is absent, log the expected/resolved path and
return Vision.
- If the provider exists but its resolved location is missing, return Vision.
- Otherwise return a new
RawCullCLIPSimilarityService around the validated
provider and supply a factory that can reconstruct a provider from the exact
validated location for finite-vector recovery.
The service value can change while RawCullSimilarityFeature and
SimilarityScoringModel retain their identities. Backend descriptors determine
whether existing artifacts are still compatible.
Semantic search is constructed only from a currently validated CLIP provider.
The provider itself satisfies both TextEmbeddingProviding and
ImageTextSimilarityComparing, so RawCullCLIPSemanticSearchService can use
the same model identity as the cached image embeddings.
Model identity at Review admission
The live Review backend accepts Qwen when the installed bundle hash and encoder contract match its expected configuration: a 448 × 448 stretch input, 196 image tokens and a 4096-token context. For CLIP it recognizes two bundle hashes and records the corresponding 224- or 256-pixel encoder geometry. An unrecognized CLIP hash leaves Review without CLIP relevance. The SAM entry records the segmenter identity and source-normalized mask preprocessing. A preset requests only its participating models. For example, Focus check skips Qwen bundle hashing entirely. CombinedReviewLiveBackend
The backend also stores a runtime-version string containing historical abbreviated revisions and the OS version. That string participates in saved evidence identity. Use the application lockfile for the actual Swift package revisions in this build.
Qwen model lifetime
Validation cancels active generation, advances the model generation, checks vision modality and retains a provider. The first request lazily constructs the vision-language model. Subsequent requests can reuse that model, each with a fresh session. A generation gate limits responses to one at a time. A request waiting for its turn rechecks its captured generation after admission. After model loading and response generation the actor checks cancellation and generation again before publishing text. QwenInferenceRuntime
Shared inference and Vision scheduling
The app creates one Qwen inference actor. Review uses it through its live backend. The in-app burst batch and MCP follow-ups use the structured assessment interface. The latter binds work to a model generation and validates the requested findings before publication. The shared Review lease coordinates exclusive work within the app. MCP also has a cross-process worker lock and authorization checks for shared jobs. An in-app batch writes session entries using the open catalog’s access. MCP results use the job’s catalog grant. QwenInferenceRuntime · BurstBatchAssessment · MCPAnalysisController+FollowUp
Vision similarity has a different scheduling constraint. RawCull injects RawCullVisionWorkSerializer into its feature-print backend. That adapter forwards Vision request bodies to PhotoAnalysisKit’s process-wide serial queue. Waiting tasks suspend while the queue executes the blocking Vision request. Image decoding can proceed concurrently. Concurrency
For preset requirements, evidence limits and culling actions, see AI Models in RawCull.