### Index a PDF and search it locally Source: https://github.com/startrail-org/pixelrag/blob/main/README.md End-to-end example: install the index and pdf extras, download a sample PDF, create a config with device: auto, build the index (~3 min on Apple M-series, ~1 min on GPU), serve it, and query it. Requires poppler for PDF rendering. ```bash pip install 'pixelrag[index,pdf]' # 1. Grab a sample PDF (or use your own) curl -L -o paper.pdf https://raw.githubusercontent.com/StarTrail-org/PixelRAG/main/assets/pixelrag-paper.pdf # 2. Create config (device: auto picks MPS on Mac, CUDA on Linux) cat > pixelrag.yaml << 'EOF' source: type: local path: ./paper.pdf embed: model: Qwen/Qwen3-VL-Embedding-2B device: auto output: ./paper_index EOF # 3. Build the index (~3 min on Apple M-series, ~1 min on GPU) pixelrag index build # 4. Serve it pixelrag serve --index-dir ./paper_index --port 30001 # 5. Search — should return page 2 (the overview diagram) curl -X POST http://localhost:30001/search \ -H "Content-Type: application/json" \ -d '{"queries": [{"text": "Overview of PixelRAG and the diagram"}], "n_docs": 1}' ``` -------------------------------- ### One-time setup with system dependencies Source: https://github.com/startrail-org/pixelrag/blob/main/demos/quickstart.ipynb Installs pixelrag and required system libraries for headless Chrome on Linux. Needs Python >= 3.12. The hosted search API needs no extra setup. ```python # One-time setup (~1 min). Needs Python >= 3.12 (Colab's default runtime). # pixelshot's headless-Chrome renderer also needs a few system libs on a # fresh Colab/Linux VM; the hosted search API needs nothing. %pip install -q pixelrag import shutil import subprocess import sys if sys.platform == "linux" and shutil.which("apt-get"): libs = ( "libnss3 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 " "libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2" ) subprocess.run(f"apt-get -qq install -y {libs}", shell=True, check=False) print("ready") ``` -------------------------------- ### Search a pre-built index with pixelrag serve Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Install the serve extra, download a pre-built FAISS index from Hugging Face (base index ~217G), start the API on port 30001, and query it with curl. The dataset repo contains four indexes; this example fetches only the base one. ```bash pip install 'pixelrag[serve]' # Download a pre-built index from Hugging Face. The dataset repo holds four FAISS indexes # (base/LoRA Wikipedia pixel, Wikipedia text, news pixel); grab just the base one (~217G) here. huggingface-cli download StarTrail-org/pixelrag-faiss-indexes \ --repo-type dataset --include "search_index_normed_v2/*" --local-dir ./index # Serve, then query pixelrag serve --index-dir ./index/search_index_normed_v2 --port 30001 curl -X POST http://localhost:30001/search \ -H "Content-Type: application/json" \ -d '{"queries": [{"text": "What is the capital of France?"}], "n_docs": 5}' ``` -------------------------------- ### Install PixelRAG via pip Source: https://github.com/startrail-org/pixelrag/blob/main/demos/quickstart.ipynb Installs the pixelrag package from PyPI. ```bash pip install pixelrag ``` -------------------------------- ### Install and run standalone embed tools Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Install the embed extra and run chunk, embed, and build-index stages independently without the orchestrator. The embed command uses --gpu-ids to specify GPUs. ```bash pip install 'pixelrag[embed]' pixelrag chunk --tiles-dir ./tiles pixelrag embed --shard-dir ./tiles --output-dir ./embeddings --gpu-ids 0,1 pixelrag build-index --embeddings-dir ./embeddings --output-dir ./index ``` -------------------------------- ### Qdrant backend: build-index, append, recreate, and serve Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Install the serve/qdrant or index/qdrant extras, then build an index against a Qdrant server, add documents to an existing collection with --append, replace a collection with --recreate, and serve the collection. PixelRAG reads the backend from summary.json. ```bash pip install 'pixelrag[serve,qdrant]' # or 'pixelrag[index,qdrant]' ``` ```bash # Build against a Qdrant server. # Start one locally with: docker run -p 6333:6333 qdrant/qdrant pixelrag build-index --embeddings-dir ./embeddings --output-dir ./index \ --backend qdrant --qdrant-url http://localhost:6333 --collection pixelrag \ --qdrant-quantization-config ./quantization.json ``` ```bash # Add documents to an existing collection. pixelrag build-index --embeddings-dir ./more --output-dir ./index \ --backend qdrant --qdrant-url http://localhost:6333 --collection pixelrag --append ``` ```bash # Replace an existing collection and its configuration. pixelrag build-index --embeddings-dir ./embeddings --output-dir ./index \ --backend qdrant --qdrant-url http://localhost:6333 --collection pixelrag --recreate ``` ```bash # Serve the collection. PixelRAG reads the backend from summary.json. pixelrag serve --index-dir ./index --qdrant-url http://localhost:6333 \ --qdrant-client-config ./qdrant-client.json --port 30001 ``` -------------------------------- ### Build an index from local documents with pixelrag index Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Install the index extra, create a pixelrag.yaml config for a local folder, then build and serve the index. Works on Linux (CUDA) and macOS (Apple Silicon / MPS); device: auto selects the best backend. ```bash pip install 'pixelrag[index]' # Create pixelrag.yaml cat > pixelrag.yaml << 'EOF' source: type: local path: ./my_docs embed: model: Qwen/Qwen3-VL-Embedding-2B device: auto # cuda on Linux, mps on macOS, cpu as fallback output: ./my_index EOF # Build, then serve pixelrag index build pixelrag serve --index-dir ./my_index --port 30001 ``` -------------------------------- ### Quick Start: Install, Convert, Train, and Eval Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/swift_training.md End-to-end workflow for training with ms-swift. Requires uv sync, data conversion, training with 2 GPUs, adapter key remap, and BiQwen3 evaluation. Note: if --num-hard-negatives > 0, eval data must also have negatives or swift will crash. ```bash # 0. Install uv sync # 1. Convert data from contrastors format to swift format uv run python convert_data_for_swift.py \ --input training/data/train_hn.jsonl --output data/train_hn_swift.jsonl uv run python convert_data_for_swift.py \ --input training/data/eval.jsonl --output data/eval_swift.jsonl # 2. Train (2 GPUs, best config) CUDA_VISIBLE_DEVICES=1,2 uv run python train_swift.py \ --train-jsonl data/train_hn_swift.jsonl \ --eval-jsonl data/eval_swift.jsonl \ --num-hard-negatives 5 \ --batch-size 4 \ --lr 1e-5 \ --max-steps 50 \ --warmup-steps 20 \ --eval-steps 25 \ --save-steps 50 \ --nproc-per-node 2 # 3. Remap adapter keys for BiQwen3 eval compatibility # (see "Adapter Key Remap" section below) # 4. Eval with BiQwen3 cd /home/user/Vis-RAG/agent && \ CUDA_VISIBLE_DEVICES=4 uv run python scripts/eval_lora_checkpoint.py \ /path/to/checkpoint-biqwen3 --tiles-dir tiles-hard-mini-v6 ``` -------------------------------- ### Ask Claude to screenshot and summarize a page Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Example commands that ask Claude to screenshot a URL and summarize or explain content. The skill calls pixelshot (Playwright/CDP) locally; no MCP server or backend is required. ```bash claude -p "screenshot https://news.ycombinator.com and summarize the top stories" claude -p "screenshot https://arxiv.org/abs/2404.12387 and explain the key findings" ``` -------------------------------- ### Run PixelRAG API in Docker and Query with curl Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Starts the PixelRAG API container with docker compose and sends a search request to the /search endpoint. The container runs as root with Chrome's sandbox disabled, so keep it isolated and avoid untrusted pages. Populate the pixelrag-index volume with a pre-built index before relying on it. ```bash docker compose up --build # then query it curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{"queries": [{"text": "What is the capital of France?"}], "n_docs": 5}' ``` -------------------------------- ### Serve Qwen3-VL-4B-Instruct with vLLM Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/reproduce_v8r.md Starts the vLLM reader on a separate GPU from training. Requires the pinned serving environment in `serving/vllm/` (or `serve/`). Verify with `curl -s http://localhost:8200/v1/models`. ```bash cd serving/vllm # (or serve/) — has its own uv.lock for vLLM uv sync CUDA_VISIBLE_DEVICES= uv run vllm serve Qwen/Qwen3-VL-4B-Instruct \ --dtype auto --port 8200 --max-model-len 65536 \ --gpu-memory-utilization 0.8 --api-key dummy # verify: curl -s http://localhost:8200/v1/models ``` -------------------------------- ### Install pixelshot CLI and Claude pixelbrowse plugin Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Installs the pixelshot CLI via uv tool (or pipx) and adds the pixelbrowse plugin to Claude Code. Use uv tool or pipx to keep pixelshot on PATH; a plain pip install into a project venv may leave it off PATH. ```bash uv tool install pixelrag # pixelshot on PATH (or: pipx install pixelrag) claude plugin marketplace add StarTrail-Org/PixelRAG claude plugin install pixelbrowse@pixelrag-plugins ``` -------------------------------- ### Benchmark and production capture with CDPPhasedStrategy Source: https://github.com/startrail-org/pixelrag/blob/main/docs/screenshot-throughput-optimization.md Use the bench harness to measure capture-only throughput, excluding worker startup cost. The bench timer starts after setup, so at 48 workers the ~49s startup is not counted. Production uses rawFilePath with .jpg extension for Chrome-side JPEG encode. ```python from pixelrag_render.strategies.cdp_phased import CDPPhasedStrategy from pixelrag_render.bench import Bench # Benchmark (with GT pixel verification) bench = Bench(zim_path="...", chrome_path="...", output_dir="./results", kiwix_url="http://localhost:9461") strategy = CDPPhasedStrategy(chrome_path="...", n_workers=48, capture_limit=48, fmt="raw") result = await bench.run(strategy) # {"tiles_per_s": 98, "correct_pct": 100, ...} # Production (JPEG files on disk) # Use rawFilePath with .jpg extension for Chrome-side JPEG encode: await conn.cdp("Page.captureScreenshot", { "rawFilePath": "/output/tile.jpg", # .jpg → JPEG encode in ThreadPool "fromSurface": True, "optimizeForSpeed": True, "clip": {"x": 0, "y": 0, "width": 875, "height": 8192, "scale": 1} }) ``` -------------------------------- ### Serve Qwen3-VL-4B with vLLM Source: https://github.com/startrail-org/pixelrag/blob/main/train/CLAUDE.md Starts a vLLM server for Qwen3-VL-4B-Instruct. Must be run from the serving/vllm subproject to use the pinned dependency versions. ```bash cd serving/vllm uv sync # first time only uv run vllm serve Qwen/Qwen3-VL-4B-Instruct \ --dtype auto --port 8201 --max-model-len 65536 \ --gpu-memory-utilization 0.8 --api-key dummy ``` -------------------------------- ### Search the hosted Wikipedia index with curl Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Searches a hosted index of 8.28M Wikipedia pages via the live API at https://api.pixelrag.ai. No setup or API key required; the endpoint also accepts an image as the query for visual search. ```bash # Search a hosted index of 8.28M Wikipedia pages — no setup, runs against the live API curl -X POST https://api.pixelrag.ai/search \ -H "Content-Type: application/json" \ -d '{"queries": [{"text": "What is the capital of France?"}], "n_docs": 5}' ``` -------------------------------- ### Render a page to screenshot tiles with pixelshot Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Renders any page or document to screenshot tiles. The --output flag specifies the directory for the generated tiles. ```bash # Render any page or document to screenshot tiles pixelshot https://en.wikipedia.org/wiki/Python --output ./tiles ``` -------------------------------- ### Qdrant quantization configuration JSON Source: https://github.com/startrail-org/pixelrag/blob/main/README.md JSON file passed to --qdrant-quantization-config to configure Qdrant quantization. The example uses scalar int8 quantization with quantile 0.99 and always_ram true. ```json { "scalar": { "type": "int8", "quantile": 0.99, "always_ram": true } } ``` -------------------------------- ### Configure Qdrant backend in pixelrag.yaml Source: https://github.com/startrail-org/pixelrag/blob/main/README.md YAML configuration for the orchestrator to use the Qdrant backend. Set append: true or recreate: true when the collection already exists. ```yaml index: backend: qdrant qdrant_url: http://localhost:6333 collection: pixelrag client_config: ./qdrant-client.json quantization_config: ./quantization.json # Set append: true or recreate: true when the collection already exists. ``` -------------------------------- ### Serve Qwen3-VL-4B-Instruct with vLLM Source: https://github.com/startrail-org/pixelrag/blob/main/train/README.md Starts a vLLM server for the Qwen3-VL-4B-Instruct reader on a separate GPU from training. Uses the pinned serving env in ../serving/vllm/ and listens on port 8200 with an API key. ```bash cd ../serving/vllm uv sync CUDA_VISIBLE_DEVICES= uv run vllm serve Qwen/Qwen3-VL-4B-Instruct \ --dtype auto --port 8200 --max-model-len 65536 \ --gpu-memory-utilization 0.8 --api-key dummy # verify: curl -s http://localhost:8200/v1/models ``` -------------------------------- ### tiles.json manifest example Source: https://github.com/startrail-org/pixelrag/blob/main/plugin/skills/pixelbrowse/SKILL.md Example of the tiles.json manifest produced by pixelshot. It lists all tile files, page height, tile height, and a complete flag. Use it to know how many tiles to read and to detect incomplete captures. ```json {"url": "...", "page_height": 29184, "tile_height": 1568, "tiles": ["tile_0000.jpg", "..."], "complete": true} ``` -------------------------------- ### Render a single page to tiles with render_url Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Use the Python API to render a web page into screenshot tiles, e.g., for an agent to read. Requires the pixelrag_render module. ```python from pixelrag_render import render_url # render a single page to tiles — e.g. for an agent to read tiles = render_url("https://en.wikipedia.org/wiki/Python", "./tiles") ``` -------------------------------- ### Render a URL to screenshot tiles with pixelshot Source: https://github.com/startrail-org/pixelrag/blob/main/demos/quickstart.ipynb Runs the pixelshot CLI to convert a Wikipedia URL into tiled JPEG screenshots. First run downloads headless Chrome. Displays the first tile as an image. ```python import subprocess from pathlib import Path from IPython.display import Image, display subprocess.run( [ "pixelshot", "https://en.wikipedia.org/wiki/Terracotta_Army", "--output", "./demo_tiles", ], check=True, ) first_tile = sorted(Path("./demo_tiles").glob("*/tile_*.jpg"))[0] print("rendered →", first_tile) display(Image(filename=str(first_tile), width=520)) ``` -------------------------------- ### Install pixelrag with extras Source: https://github.com/startrail-org/pixelrag/blob/main/RELEASING.md Install the core pixelrag package (rendering only, no torch) or add extras for heavy ML stages: [serve] for search API, also [embed], [index], [all]. ```bash pip install pixelrag # pixelshot + pixelrag umbrella (no torch) pip install 'pixelrag[serve]' # + search API (also [embed], [index], [all]) ``` -------------------------------- ### Install demo environment and run search with fetch Source: https://github.com/startrail-org/pixelrag/blob/main/demos/parallel_search/README.md Installs the isolated demo environment and runs the search script with a query, limit, and fetch flag. Anonymous search uses Fast mode; no account or API key required. Output is saved to demos/parallel_search/output/results.json. ```bash uv sync --project demos/parallel_search --locked uv run --project demos/parallel_search python demos/parallel_search/run.py \ "Find explanations of retrieval augmented generation" \ --query "retrieval augmented generation overview" --limit 2 --fetch ``` -------------------------------- ### Quick Start Commands for Contrastors Training Source: https://github.com/startrail-org/pixelrag/blob/main/train/CONTRASTORS.md Commands to run contrastors training on single or multiple GPUs, with optional hard negatives and checkpoint resume. Requires a Python environment at .venv-sglang/bin and the training script training/train_contrastors.py. For hard negatives, train_hn.jsonl must be generated by mine_hard_negatives.py. ```bash PYTHON=.venv-sglang/bin/python # Single GPU CUDA_VISIBLE_DEVICES=3 $PYTHON training/train_contrastors.py \ --max-steps 500 --batch-size 4 --grad-cache-chunk 2 # Multi-GPU (5 GPUs, cross-GPU negatives + GradCache) CUDA_VISIBLE_DEVICES=3,4,5,6,7 .venv-sglang/bin/torchrun --nproc_per_node=5 \ training/train_contrastors.py --max-steps 500 --batch-size 8 --grad-cache-chunk 2 # With hard negatives (requires train_hn.jsonl from mine_hard_negatives.py) CUDA_VISIBLE_DEVICES=3,4,5,6,7 .venv-sglang/bin/torchrun --nproc_per_node=5 \ training/train_contrastors.py --train-jsonl training/data/train_hn.jsonl \ --num-hard-negatives 2 --batch-size 4 --grad-cache-chunk 2 # Resume from checkpoint $PYTHON training/train_contrastors.py \ --resume training/output_contrastors/checkpoint-200 ``` -------------------------------- ### Set up environment with uv sync (base and reader extra) Source: https://github.com/startrail-org/pixelrag/blob/main/eval/README.md Run from the eval directory. The base install is a pure HTTP client with no torch/vllm; the optional reader extra adds vLLM 0.19.0 for self-hosting the Qwen3.5-4B reader on a CUDA GPU. vLLM requires numpy<2.3, hence the bound. ```bash cd eval uv sync --frozen # base client (retrieval + reader + grader over HTTP); Python 3.12 # Optional — to self-host the Qwen3.5-4B reader from this package (needs a CUDA GPU): uv sync --frozen --extra reader # also installs vLLM 0.19.0 into eval/.venv ``` -------------------------------- ### Generate text query pairs with generate_text_query_pairs.py Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/synthetic_data_pipeline.md Runs the text warmup data generation script. Queries the SQLite DB for articles with ≥6 chunks, selects a long natural prose paragraph, sends it to Gemini with 5-shot examples, filters for natural self-contained questions, and verifies the supporting span exists verbatim. Expected yield is ~40% (21K pairs from 52K articles) at a cost of ~$110 with Flash Lite. ```bash uv run python generate_text_query_pairs.py \ --db-path /opt/dlami/nvme/text_embeddings_1024/text_baseline.db \ --num-articles 52000 \ --model gemini-3.1-flash-lite-preview \ --output text_query_pairs.jsonl \ --min-article-chunks 6 \ --min-paragraph-words 60 ``` -------------------------------- ### Set up Google Cloud ADC and OpenAI API key Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/synthetic_data_pipeline.md One-time setup for API keys. Google Cloud ADC is used by Gemini scripts via Vertex AI; OPENAI_API_KEY is used by GPT-4o scripts. Optionally set OPENAI_BASE_URL if your key requires it. ```bash # Google Cloud (one-time setup) gcloud auth application-default login # OpenAI export OPENAI_API_KEY="sk-proj-..." export OPENAI_BASE_URL="https://us.api.openai.com/v1" # if your key requires this ``` -------------------------------- ### Train contrastors with LoRA ViT and text warmup Source: https://github.com/startrail-org/pixelrag/blob/main/train/README.md Run the main training script from the train directory. Adjust $DATA_ROOT and $OUTPUT_DIR paths. Key flags: --lora-vit applies LoRA to the ViT encoder, --text-warmup-steps 50 enables text-only warmup, --num-hard-negatives 2 matches the dataset's mined negatives, and --grad-cache-chunk 4 keeps memory proportional to chunk size. The --test-eval-steps 50 triggers full retrieval and QA evaluation every 50 steps, requiring vLLM and a grader. Startup logs should show trainable params 25,427,968 and loaded data counts to confirm correct setup. ```bash cd train CUDA_VISIBLE_DEVICES= uv run python train_contrastors.py \ --data-split-dir "$DATA_ROOT/screenshot-training-natural-filtered-v2" \ --text-warmup-steps 50 \ --text-data-dir "$DATA_ROOT/text-qa-pair" \ --test-data "$DATA_ROOT/screenshot-training/test_miniv8/test_miniv8.json" \ --max-steps 350 \ --batch-size 64 \ --grad-cache-chunk 4 \ --num-hard-negatives 2 \ --lr 7e-6 \ --warmup-steps 20 \ --scheduler cosine \ --test-batch-size 16 \ --eval-steps 25 \ --test-eval-steps 50 \ --save-steps 50 \ --max-num-visual-tokens 4096 \ --lora-vit \ --simpleqa-max-examples 1000 \ --vllm-url http://localhost:8200/v1 \ --vllm-model Qwen/Qwen3-VL-4B-Instruct \ --wandb-run-name v8r \ --output-dir "$OUTPUT_DIR/v8_r_warmup50_lr7e6_lora_vit_350" ``` -------------------------------- ### Install dependencies with uv sync Source: https://github.com/startrail-org/pixelrag/blob/main/train/README.md Creates a .venv with the exact locked versions from pyproject.toml and uv.lock. Run from the train directory. Pinned versions are mandatory to avoid silent numerical drift. ```bash cd train uv sync # creates .venv with the exact locked versions ``` -------------------------------- ### Install dependencies with uv sync Source: https://github.com/startrail-org/pixelrag/blob/main/train/CLAUDE.md Installs pinned versions of PyTorch, cuDNN, and transformers from pyproject.toml and lockfile. Always use `uv run` to ensure the locked environment is used. ```bash uv sync ``` -------------------------------- ### pixelshot CLI: render web pages and PDFs to tiles Source: https://github.com/startrail-org/pixelrag/blob/main/README.md Command-line rendering of web pages and PDFs to tiles using headless Chromium via CDP. PDF rendering requires poppler and the pdf extra. URLs and local files can be mixed. On non-linux-x64 systems, uses system Chrome/Chromium or Playwright's Chromium; set CHROME_PATH if needed. ```bash # Web page → tiles (headless Chromium via CDP) pixelshot https://en.wikipedia.org/wiki/Python -o ./tiles ``` ```bash # PDF → tiles (requires poppler; install the pdf extra: pip install 'pixelrag[pdf]') curl -sL -o paper.pdf https://arxiv.org/pdf/2503.09516 pixelshot paper.pdf -o ./tiles --dpi 200 ``` ```bash # URLs and local files can be mixed freely pixelshot https://github.com/StarTrail-org/PixelRAG paper.pdf -o ./tiles ``` -------------------------------- ### Search the hosted Wikipedia index via API Source: https://github.com/startrail-org/pixelrag/blob/main/demos/quickstart.ipynb Queries the live PixelRAG API (8.28M pages) with a Chinese query. Each hit returns tile coordinates; fetches and displays the matching screenshot tile. ```python import requests from IPython.display import Image, display API = "https://api.pixelrag.ai" hits = requests.post( f"{API}/search", json={"queries": [{"text": "兵马俑"}], "n_docs": 2} ).json()["results"][0]["hits"] for h in hits: print(f"{h['score']:.3f} {h['url']}") tile = f"{API}/tile/{h['article_id']}/{h['tile_index']}/{h['chunk_index']}" display( Image(data=requests.get(tile).content, width=420) ) # embed so it shows on GitHub ``` -------------------------------- ### Run benchmark with Cheaper Inference reader Source: https://github.com/startrail-org/pixelrag/blob/main/eval/README.md Selects the Cheaper Inference reader with `--cheaperinference`. Requires `CHEAPER_INFERENCE_API_KEY` and a bare model ID from the model list. For screenshot benchmarks, use `gpt-5.4-mini` or `gpt-5.4`; this text-only example does not use retrieval. `--api-key` overrides the environment key, and other providers' keys are never used. ```bash export CHEAPER_INFERENCE_API_KEY=ci_live_... python run_bench.py --task simpleqa --model gpt-5.4-mini \ --cheaperinference --num-examples 1 --max-concurrent 1 --max-tokens 256 ``` -------------------------------- ### pixelshot CLI usage examples Source: https://github.com/startrail-org/pixelrag/blob/main/plugin/skills/pixelbrowse/SKILL.md Shows common pixelshot invocations: screenshot a URL with Claude-optimized tile height, parallel screenshots, wider viewport, and PDF rendering. Always use --tile-height 1568 for visual reading and --wait-network-idle for URLs to avoid blank captures. ```bash # Screenshot a URL (optimized for Claude's vision: 1568px tile height) pixelshot --output /tmp/pixelbrowse --tile-height 1568 --wait-network-idle # Screenshot multiple URLs in parallel pixelshot --output /tmp/pixelbrowse --tile-height 1568 --wait-network-idle --workers 4 # Wider viewport for desktop layouts pixelshot --output /tmp/pixelbrowse --tile-height 1568 --viewport-width 1280 --wait-network-idle # Render a PDF pixelshot document.pdf --output /tmp/pixelbrowse ``` -------------------------------- ### Pipeline architecture diagram Source: https://github.com/startrail-org/pixelrag/blob/main/README.md ASCII diagram showing the relationships between the main pipeline stages: render, index, embed, serve, and train. The index stage orchestrates render and embed, while serve is independent and train connects to serve via HTTP. ```text render ←── index ──→ embed serve (independent) train → serve (HTTP) ``` -------------------------------- ### Install pixelrag via pip Source: https://github.com/startrail-org/pixelrag/blob/main/plugin/opencode/README.md Install the pixelrag package to provide the pixelshot command. Alternatively, use uv tool install pixelrag. ```bash pip install pixelrag # provides the pixelshot command (or: uv tool install pixelrag) ``` -------------------------------- ### Run NQ benchmark against public API with run_bench.py Source: https://github.com/startrail-org/pixelrag/blob/main/eval/README.md Drives run_bench.py directly to run a benchmark against the public API (mode 2) because reproduce.sh hardcodes localhost. This example runs the NQ task with the Qwen/Qwen3.5-4B model, uses the public base endpoint, and grades with an LLM judge (the paper used --llm-judge). Requires READER_URL environment variable and an API key. ```bash .venv/bin/python run_bench.py --task nq --model Qwen/Qwen3.5-4B \ --api-base "$READER_URL" --api-key dummy --no-think \ --retrieval-top-k 5 --reader-top-k 3 --num-examples 1000 --max-tokens 200 \ --local-api --local-api-url http://api.pixelrag.ai:30001/search \ --query-instruction "Retrieve images or text relevant to the user's query." ``` -------------------------------- ### Serve the built index Source: https://github.com/startrail-org/pixelrag/blob/main/skill/pixelrag.md Starts the PixelRAG server for the index built in the previous step, using environment variables to point to the index directory and articles JSON. ```bash PIXELRAG_INDEX_DIR=./my_index PIXELRAG_ARTICLES_JSON=./my_index/articles.json \ uv run pixelrag serve --port 31337 ``` -------------------------------- ### Install pixelbrowse plugin Source: https://github.com/startrail-org/pixelrag/blob/main/plugin/README.md Install the pixelshot command and add the plugin to Claude Code. For local development, use `claude --plugin-dir /path/to/PixelRAG/plugin`. ```bash pip install pixelrag # provides the pixelshot command claude plugin marketplace add StarTrail-org/PixelRAG claude plugin install pixelbrowse@pixelrag-plugins ``` -------------------------------- ### Run a benchmark cell with reproduce.sh Source: https://github.com/startrail-org/pixelrag/blob/main/eval/README.md Runs a benchmark cell against self-hosted serves on localhost. The bench argument selects the dataset (nq, nqt, sqa, mms, evqa, livevqa) and retrieval selects the mode (naive, traf, base, lora). NUM overrides the example count for a quick smoke test. A preflight checks that required serves are up with the expected index and prints the exact pixelrag serve command if not. ```bash bash reproduce.sh # bench = nq | nqt | sqa | mms | evqa | livevqa # retrieval = naive | traf | base | lora # e.g. bash reproduce.sh evqa base # -> prints Score: 0.4xx bash reproduce.sh mms lora NUM=20 bash reproduce.sh nq traf # NUM overrides the example count for a quick smoke ``` -------------------------------- ### Install and verify Codex systemd drop-in Source: https://github.com/startrail-org/pixelrag/blob/main/deploy/CODEX.md Installs the production drop-in pixelrag-agent-codex.conf, reloads systemd, restarts the service, and checks health/ready endpoints. The health response includes backend: "codex". Removing the drop-in and restarting restores the original Claude deployment. ```sh sudo install -m 0644 deploy/pixelrag-agent-codex.conf \ /etc/systemd/system/pixelrag-agent.service.d/codex.conf sudo systemctl daemon-reload sudo systemctl restart pixelrag-agent.service curl --fail http://localhost:30010/health curl --fail http://localhost:30010/ready ``` -------------------------------- ### Run Atlas Cloud reader with --atlascloud Source: https://github.com/startrail-org/pixelrag/blob/main/eval/README.md Selects the Atlas Cloud reader explicitly with --atlascloud; other readers are unchanged. Requires ATLASCLOUD_API_KEY and an exact model ID from the live catalog. This text-only example does not use retrieval; for screenshot benchmarks select a model supporting image input. Model IDs are forwarded unchanged to https://api.atlascloud.ai/v1, including IDs containing 'gemini'; they do not select the native Google SDK. --api-key overrides ATLASCLOUD_API_KEY, and other providers' environment keys are never used. Do not combine this option with another provider flag or --api-base. Atlas requests are not automatically retried, including timeouts, connection errors and rate limits, to avoid duplicating billable generation requests. ```bash export ATLASCLOUD_API_KEY=your-api-key python run_bench.py --task simpleqa --model deepseek-ai/deepseek-v3.2 \ --atlascloud --num-examples 1 --max-concurrent 1 --max-tokens 256 ``` -------------------------------- ### Export frozen-retrieval benchmark with dump_bench.sh and pack_bench.py Source: https://github.com/startrail-org/pixelrag/blob/main/eval/README.md Two-step workflow to produce the frozen-retrieval benchmark for the pixelrag-bench dataset. First run dump_bench.sh to retrieve only (resumable, one directory per bench), then pack_bench.py to pack into one Parquet config per bench with images embedded. dump_bench.sh uses run_bench.py --dump-retrieval with the same example sets, query images, instruction and nprobe as the LoRA cells of reproduce.sh. Hits with missing tiles are recorded in /missing_tiles.jsonl; pack_bench.py refuses to pack until each is filled or listed in --allow-missing as lost. ```bash # 1. retrieve only (no reader); resumable, one directory per bench LORA_URL=http://localhost:30096/search bash dump_bench.sh # 2. pack into one Parquet config per bench, images embedded .venv/bin/python pack_bench.py --commit ``` -------------------------------- ### Verify fine-tuned vs base embeddings and gradient correctness tests Source: https://github.com/startrail-org/pixelrag/blob/main/train/CLAUDE.md Runs verification of fine-tuned vs base embeddings with the specified adapter and max pairs, then executes gradient correctness tests for single and multi-GPU setups. Requires CUDA_VISIBLE_DEVICES set appropriately and uses uv run. ```bash # Verify fine-tuned vs base embeddings CUDA_VISIBLE_DEVICES=0 uv run python verify_embeddings.py \ --adapter training/output_nvme/output_contrastors/checkpoint-500 --max-pairs 100 # Gradient correctness tests CUDA_VISIBLE_DEVICES=0 uv run python tests/test_grad_equivalence.py CUDA_VISIBLE_DEVICES=0,1 uv run torchrun --nproc_per_node=2 tests/test_grad_multi_gpu.py ``` -------------------------------- ### Run agent server with Codex backend Source: https://github.com/startrail-org/pixelrag/blob/main/deploy/CODEX.md Starts the standalone agent server with CHAT_BACKEND=codex, using the Codex CLI via codex exec --json. Requires Node 22+, Codex CLI 0.159.1, and codex login under the service's OS account; no OpenAI API key needed. CHAT_CODEX_MODEL optionally selects a model, CHAT_CODEX_TIMEOUT_MS defaults to 180000, and CHAT_MAX_TURNS bounds MCP tool calls. ```sh CHAT_BACKEND=codex CODEX_BIN=/home/zlab-ssd1/.local/bin/codex \ PIXELRAG_SEARCH_URL=http://localhost:30001 AGENT_PORT=30011 \ /home/yichuan/.nix-profile/bin/node web/agent-server.mjs ``` -------------------------------- ### Run VQA hard negative filtering on a sample file Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/training_dev_notes.md Filters mined retrieval candidates for false negatives using a VLM. Requires OPENAI_API_KEY. Reads retrieve_top20, skips the positive chunk_path, checks up to --candidate-k (default 10) non-positive candidates, and keeps candidates judged WRONG or CANNOT_ANSWER as hard negatives. Stops after collecting --num-hard-negatives and skips the example if not enough are found. ```bash OPENAI_API_KEY=... python filter_hard_negatives_vqa.py \ --input /tmp/sample_100_hn.jsonl \ --output /tmp/sample_100_hn_v2.jsonl \ --reviews-output /tmp/sample_100_hn_v2.reviews.jsonl \ --summary-output /tmp/sample_100_hn_v2.summary.json \ --candidate-k 10 \ --num-hard-negatives 2 \ --concurrency 8 ``` -------------------------------- ### Check search API health and start serving Source: https://github.com/startrail-org/pixelrag/blob/main/skill/pixelrag.md Checks if the search API is running via /health, then starts serving a pre-built index on port 30001 in the background. ```bash # Check if search API is running curl -s http://localhost:30001/health # Start serving a pre-built index PIXELRAG_INDEX_DIR=/home/yichuan/pixelrag-data/text_search_index_1024 \ PIXELRAG_ARTICLES_JSON=/home/yichuan/pixelrag-data/articles.json \ uv run pixelrag serve --port 30001 & ``` -------------------------------- ### Download text-warmup data text-qa-pair Source: https://github.com/startrail-org/pixelrag/blob/main/train/README.md Downloads the ~1.8 GB text-only dataset with query→passage pairs and hard negatives for the 50-step text warmup. Already in the chunk_*/filtered_hn.jsonl layout the trainer expects. ```bash hf download Chrisyichuan/text-qa-pair \ --repo-type dataset \ --local-dir "$DATA_ROOT/text-qa-pair" ``` -------------------------------- ### Prepare, package, and upload Hugging Face dataset Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/training_dev_notes.md Three sequential commands for regenerating or uploading a Hugging Face dataset: prepare the dataset folder by converting absolute paths to relative paths and hardlinking images, package images into tar shards, then upload to Hugging Face. Upload requires a Hugging Face token with write permission. ```bash # Prepare HF dataset folder: convert absolute paths to relative paths and hardlink images. python prepare_hf_dataset.py \ --split-dir training/data/lite-query-v2-full-filtered-hn-v2-chunks/split \ --image-root /opt/dlami/nvme/kiwix_tiles \ --output-dir hf_dataset_export/screenshot-training # Package images into tar shards. python package_hf_image_shards.py \ --source-dir hf_dataset_export/screenshot-training \ --output-dir hf_dataset_export_sharded/screenshot-training # Upload to Hugging Face. python upload_hf_dataset.py \ --local-dir hf_dataset_export_sharded/screenshot-training ``` -------------------------------- ### GET /health Source: https://github.com/startrail-org/pixelrag/blob/main/skill/pixelrag.md Check if the PixelRAG search API is running and healthy. ```APIDOC ## [GET] /health ### Description Check if the PixelRAG search API is running and healthy. ### Method GET ### Endpoint http://localhost:30001/health ### Response #### Success Response (200) No response body specified. ``` -------------------------------- ### Add plugin to opencode.json Source: https://github.com/startrail-org/pixelrag/blob/main/plugin/opencode/README.md Add the @startrail/pixelbrowse plugin to your opencode.json configuration. opencode installs npm plugins automatically at startup. ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["@startrail/pixelbrowse"] } ``` -------------------------------- ### Generate visual query pairs (single batch) Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/synthetic_data_pipeline.md Runs generate_query_pairs.py for a single batch of 2000 pages. Requires --tiles-dir pointing to the kiwix_tiles directory and a Gemini model. Outputs a JSONL batch file. ```bash uv run python generate_query_pairs.py \ --tiles-dir /opt/dlami/nvme/kiwix_tiles \ --num-pages 2000 \ --model gemini-3.1-flash-lite-preview \ --output batches/batch_000.jsonl \ --seed 0 ``` -------------------------------- ### Search the index with curl Source: https://github.com/startrail-org/pixelrag/blob/main/skill/pixelrag.md Queries the running search API on port 30001. Requires the API to be started first. Returns JSON with hits. ```bash curl -s -X POST http://localhost:30001/search \ -H "Content-Type: application/json" \ -d '{"queries": [{"text": "YOUR QUERY"}], "n_docs": 5}' ``` -------------------------------- ### Import a shadcn/ui component in TSX Source: https://github.com/startrail-org/pixelrag/blob/main/web/README.md Use this import statement to use a shadcn/ui component in your app. The example imports the Button component from the `@/components/ui/button` path. ```tsx import { Button } from "@/components/ui/button"; ``` -------------------------------- ### Search API response JSON Source: https://github.com/startrail-org/pixelrag/blob/main/skill/pixelrag.md Example JSON response from the search API, containing a results array with hits including score, URL, and article_id. ```json { "results": [{ "hits": [ {"score": 0.73, "url": "https://en.wikipedia.org/wiki/...", "article_id": 123, ...} ] }] } ``` -------------------------------- ### Download test set test_miniv8 Source: https://github.com/startrail-org/pixelrag/blob/main/train/README.md Downloads the ~2 GB test set with 400 SimpleQA questions and 7426 candidate tiles for retrieval and QA-score eval. Uses the include filter to fetch only test_miniv8/*. ```bash hf download Chrisyichuan/screenshot-training \ --repo-type dataset --include "test_miniv8/*" \ --local-dir "$DATA_ROOT/screenshot-training" ``` -------------------------------- ### Run gradient equivalence tests (single-GPU and multi-GPU) Source: https://github.com/startrail-org/pixelrag/blob/main/train/CONTRASTORS.md Commands to execute the verified gradient equivalence test suites for train_contrastors.py. Single-GPU tests use CUDA_VISIBLE_DEVICES=2; multi-GPU tests use torchrun with 2 GPUs (2,3). ```bash CUDA_VISIBLE_DEVICES=2 python training/tests/test_grad_equivalence.py CUDA_VISIBLE_DEVICES=2,3 torchrun --nproc_per_node=2 training/tests/test_grad_multi_gpu.py ``` -------------------------------- ### Set data root directory Source: https://github.com/startrail-org/pixelrag/blob/main/train/README.md Sets DATA_ROOT to a large disk and creates the directory. Required before downloading datasets. ```bash export DATA_ROOT=/big/disk/visrag/data mkdir -p "$DATA_ROOT" ``` -------------------------------- ### LogitScale forward and clamp Source: https://github.com/startrail-org/pixelrag/blob/main/train/CONTRASTORS.md Shows the learnable log-space temperature initialization and usage. The forward pass uses exp(log_scale) without clamping to avoid gradient dead zones, and after optimizer.step() the log_scale is clamped to [0, ln(100)] following the contrastors pattern. ```python forward: similarity * exp(log_scale) # no clamp in forward (avoids gradient dead zone) after optimizer.step(): log_scale.clamp_(0, ln(100)) # contrastors pattern ``` -------------------------------- ### Launch training inside tmux session Source: https://github.com/startrail-org/pixelrag/blob/main/train/CLAUDE.md Starts a training run inside a tmux session to prevent loss on SSH disconnect. Uses tmux new-session and send-keys to run torchrun with specified GPUs, logging output to a file. Never run torchrun directly in a bare SSH terminal. ```bash # Correct approach: launch inside tmux tmux new-session -d -s train -c /home/ubuntu/wiki-screenshot-training tmux send-keys -t train "CUDA_VISIBLE_DEVICES=1,2,3 uv run torchrun --nproc_per_node=3 train_contrastors.py \ [args...] 2>&1 | tee training/output_nvme//train.log" Enter # View training output tmux attach -t train ``` -------------------------------- ### Train Qwen3-VL-4B with LlamaFactory (4 GPUs) Source: https://github.com/startrail-org/pixelrag/blob/main/train/CLAUDE.md Launches SFT training on 4 GPUs using the specified YAML config. Must be run inside tmux. ```bash cd sft/LlamaFactory && source .venv/bin/activate CUDA_VISIBLE_DEVICES=1,2,3,4 \ FORCE_TORCHRUN=1 NNODES=1 NPROC_PER_NODE=4 \ llamafactory-cli train /home/ubuntu/wiki-screenshot-training/sft/train_qwen3vl_compressed.yaml ``` -------------------------------- ### Extract training images and test tiles Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/reproduce_v8r.md Extracts training images from 1000 shards into images/ and unpacks test tiles. Training extraction is slow on networked filesystems; use fast/local storage. Test tiles are extracted into a tiles directory. ```bash # Training images (1000 shards → images/). SLOW on networked filesystems — # extract to fast/local storage. ~200K small PNGs. python "$DATA_ROOT/screenshot-training-natural-filtered-v2/extract_hf_image_shards.py" \ --dataset-dir "$DATA_ROOT/screenshot-training-natural-filtered-v2" ``` ```bash # Test tiles cd "$DATA_ROOT/screenshot-training/test_miniv8" mkdir -p tiles && tar xf tiles.tar -C tiles ``` -------------------------------- ### Run single-GPU and multi-GPU gradient equivalence tests Source: https://github.com/startrail-org/pixelrag/blob/main/train/docs/training_dev_notes.md Test commands for verifying gradient equivalence. The single-GPU command uses GradCache math, RandContext, clip_loss, and rope_deltas; the multi-GPU command uses DDP, gather, loss scaling, and gradient sync. Run the single-GPU test first, then the multi-GPU test with two GPUs. ```bash # Single-GPU: GradCache math + RandContext + clip_loss + rope_deltas CUDA_VISIBLE_DEVICES=0 uv run python tests/test_grad_equivalence.py # Multi-GPU: DDP + gather + loss scaling + gradient sync CUDA_VISIBLE_DEVICES=0,1 uv run torchrun --nproc_per_node=2 tests/test_grad_multi_gpu.py ``` -------------------------------- ### Run opencode with screenshot command Source: https://github.com/startrail-org/pixelrag/blob/main/plugin/opencode/README.md Ask opencode to look at a page using the screenshot tool. The agent calls the tool with a URL or local file and reads the resulting tile images visually. ```bash opencode run "screenshot https://news.ycombinator.com and summarize the top stories" ``` -------------------------------- ### Run demo tests Source: https://github.com/startrail-org/pixelrag/blob/main/demos/parallel_search/README.md Runs the test suite for the parallel search demo to verify functionality. ```bash uv run --project demos/parallel_search pytest demos/parallel_search/test_run.py ```