Metadata-Version: 2.4
Name: 3d-trainer
Version: 0.0.2
Summary: Train a scribble adapter for TripoSR - LoRA plus a prompt projector, distilled from TripoSR itself on captioned Objaverse renders - so that a sketch and a text prompt give a coloured 3D mesh, and export the adapter GGUF the ggk engine applies with --adapter
Author-email: gguf <info@gguf.us>
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
License-File: LICENSE
Requires-Dist: torch>=2.1
Requires-Dist: transformers>=4.51
Requires-Dist: safetensors>=0.4
Requires-Dist: huggingface_hub>=0.23
Requires-Dist: numpy>=1.24
Requires-Dist: scipy>=1.10
Requires-Dist: pillow>=9.0
Requires-Dist: gguf-connector>=3.7.5
Project-URL: Repository, https://github.com/gguf-org/ggk

# 3d-trainer

Train an adapter that makes an image-to-3D model take **a sketch and a text
prompt**, and export it as the GGUF the ggk engine applies with `--adapter`.

One recipe so far, `triposr_scribble`: a scribble adapter for
[TripoSR](https://github.com/VAST-AI-Research/TripoSR).

```bash
ggk -m triposr-nvfp4.gguf --adapter pig_triposr_scribble_adapter-f16.gguf --ref-image sheep.png -p "a sheep" -o out.glb
```

TripoSG-scribble already takes a sketch and a prompt, but its mesh is bare
geometry. TripoSR's comes out of a radiance field, so the result here is
**coloured**, and the prompt decides the colours a line drawing cannot show
(`-p "a black sheep"`).

## What it does

TripoSR is a feed-forward model: a DINO ViT turns the picture into 1025
tokens, a transformer cross-attends to them and writes a triplane, a small
NeRF MLP reads density and colour off it. It was trained on renders, and has
no text input.

The adapter changes two things and adds no layers to the transformer:

* **LoRA** (rank 32) on the linears of the image encoder and of the triplane
  transformer, so the two learn to read a line drawing;
* the **prompt** goes through a CLIP text encoder (ViT-L/14's, frozen — the
  one TripoSG-scribble uses) and a small projector, and its 77 tokens are
  appended to the image tokens the transformer already attends to.

The NeRF decoder is not touched: what comes out is a TripoSR triplane like
any other.

It is trained by **distillation from TripoSR itself**, which needs pictures
and captions but no 3D data:

| | sees | makes |
| --- | --- | --- |
| teacher: plain TripoSR | a render of an object, cut out over grey | a triplane |
| student: TripoSR + adapter | a **scribble** of that render, and its **caption** | the same triplane |

The loss compares the triplanes, and the density and colour fields at points
sampled in the scene, half of them next to the teacher's surface. A scribble
has no colours, so the student can only get them from the caption — that is
what makes the prompt count. One row in five shows the render itself on
white, in colour or in grey, so a photo still works; one in ten drops the
caption, so a sketch alone does too.

The scribbles are drawn from the render (`sketch.py`): the silhouette of its
alpha mask, inner lines from an extended difference of Gaussians or Sobel
edges, a pen of varying width and darkness, and a wobble, framed the way the
engine frames the picture. `python -m 3d_trainer sketch --image cutout.png`
shows one.

The renders and captions are [Cap3D](https://huggingface.co/datasets/tiange/Cap3D)'s
of Objaverse — the kind of picture TripoSR was trained on. Each object is a
small zip inside a 42 GB archive; the select stage reads the ones it wants
over HTTP ranges (about 1 MB an object), keeps the views taken from a sensible
height, and never downloads the archive. Your own pictures work as well: a
folder of RGBA cut-outs, `<name>.png` with the caption in `<name>.txt`
(`new --folder`).

## Running it

The package folder is `3d_trainer`, which is not a name Python can `import`
by statement, so it is run as a module:

```bash
pip install 3d-trainer           # or: cd 3d_trainer/src
python -m 3d_trainer new --project ~/3d-trainer/projects/triposr_scribble
python -m 3d_trainer download --project ~/3d-trainer/projects/triposr_scribble
python -m 3d_trainer run --project ~/3d-trainer/projects/triposr_scribble
```

`run` goes through the stages and skips what is done; interrupt it (Ctrl-C, or
`stop` from another terminal) and run it again to resume. `start` runs the
same thing detached, logging to `pipeline.log`.

| stage | | on an RTX 5090 |
| --- | --- | --- |
| `select` | 8000 captioned objects, two views each, from Cap3D | 30 min (network) |
| `teacher` | plain TripoSR's triplane of every render (1 MB each) | 21 min |
| `train` | 6000 steps at batch 8: 232 LoRA pairs + the projector, 22.4M parameters | 1 h 20 min |
| `export` | `export/adapter.safetensors`, and `<name>-f16.gguf` next to the project | seconds |
| `eval` | `eval/sheet.png` and `eval/eval.json` on held-out objects | under a minute |

Training uses gradient checkpointing and takes about 6 GB of VRAM at batch 8
(`train.grad_checkpoint`, `train.batch_size` in `project.json`).

```
python -m 3d_trainer status --project <folder>                   what is done, and the ggk command line
python -m 3d_trainer set --project <folder> --steps 12k          train longer (then `run` again)
python -m 3d_trainer preview --project <folder> --image sketch.png -p "a sheep" -p "a black sheep" --out preview.png
python -m 3d_trainer sketch --image cutout.png --out scribble.png
python -m 3d_trainer convert-adapter --input <folder>/export --output adapter-f16.gguf
```

`preview` renders what the adapter makes of a picture, one row per prompt,
with the PyTorch model — a quick look without the engine.

## The adapter GGUF

`<name>-f16.gguf` (278 MB) holds, under the names the engine looks them up by:

| tensors | |
| --- | --- |
| `image_tokenizer.<linear>.lora_down.weight`, `.lora_up.weight`, `.alpha` | 72 LoRA pairs for the DINO ViT, named after the TripoSR weight they sit beside |
| `backbone.<linear>.lora_down.weight`, `.lora_up.weight`, `.alpha` | 160 pairs for the triplane transformer |
| `text_proj.net.0`, `text_proj.net.2`, `text_proj.norm` | the prompt projector: Linear, GELU, Linear, LayerNorm |
| `text_encoder.text_model.*` | the CLIP text model, unchanged (most of the file) |

and `pig.adapter.kind = triposr-scribble` with the rest of its description in
the metadata. The base model is not in it and is not modified: the engine adds
the low-rank branches at run time, so the one adapter serves every
quantization of TripoSR (q8_0, q4_k, nvfp4).

In the engine (a `ggk` build whose TripoSR accepts `--adapter`), `--adapter-scale` scales the LoRA and
`--scribble-conf` / `--prompt-conf` weigh the picture against the prompt
(1.0 each). The picture's subject is found as for plain TripoSR — its alpha
channel, a `--mask`, or a plain backdrop removed — and put on white paper.

A photo shows its own colours, and the adapter then has nothing to ask the
prompt. So when a prompt is given and the picture is not already a line
drawing, the engine traces it into one (the silhouette and the inner
lines, as `sketch.py` draws them) and runs twice: the mesh is the one plain
TripoSR makes of the photo, and its colours are read from the field the
adapter makes of the tracing and the prompt. Without `-p`, or with `GGK_TRIPOSR_NO_TRACE=1`, the
picture is used as it is. The prompt colours what is drawn; it does not add
parts that are not in the drawing (sunglasses have to be sketched in).

## Results

The run described above (8000 objects, 6000 steps), on 48 held-out objects,
scribble + caption against the teacher's field:

| | with the caption | without |
| --- | --- | --- |
| inside/outside agreement | 0.968 | 0.967 |
| colour error (L1 on the teacher's solid) | 0.087 | 0.097 |
| triplane error (relative MSE) | 0.171 | 0.190 |

The shape comes from the drawing and the colour from the prompt: the same
hand-drawn pig gives a pink mesh with `-p "a pink pig"`, a green one with
`-p "a green pig"`, and a grey-brown one with no prompt. Surfaces are softer
than plain TripoSR's on a photo, and fine texture (a chessboard's squares, a
face) is not recovered from a caption. A colour picture is traced into a sketch by the engine
when a prompt comes with it; untraced, the picture decides and the prompt is ignored. The engine adds about
half a second to a TripoSR run (3.7 s against 3.1 s on an RTX 5090).

## Materials

| id | what | size |
| --- | --- | --- |
| `triposr` | `stabilityai/TripoSR` `model.ckpt` — the teacher and the model trained over (a TripoSR GGUF works too: `materials.triposr.path`) | 1.7 GB |
| `clip` | `openai/clip-vit-large-patch14` — the text encoder the adapter carries | 1.7 GB |
| `captions` | `tiange/Cap3D` `Cap3D_automated_Objaverse_full.csv` | 255 MB |

They go to the Hugging Face cache and are shared between projects. Set
`HF_TOKEN` (or `hf_token` in `project.json`) for faster, unthrottled reads.

## Project layout

```
project.json            the configuration; everything has a default (project.py)
pipeline.log            what the stages printed
data/index.jsonl        the selected renders: id, caption, split
data/images/<id>.png    the renders, RGBA
teacher/<id>.npy        the teacher's triplanes, f16
checkpoints/last.pt     the adapter being trained (resumable), log.csv beside it
export/                 adapter.safetensors, adapter_config.json
eval/                   sheet.png, eval.json
../<name>-f16.gguf      the adapter for ggk (export.output_dir / export.copy_to)
```

## Notes

* The student can be no better than its teacher: where TripoSR gives a flat
  or blurry back to a render, so does the adapter to its scribble.
* A scribble is drawn from a render here, not by a hand. The wobble and the
  varied pen cover a good part of the gap; drawings far from a clean outline
  (hatching, text, several objects) are outside what it was shown.
* The model licences apply to what you train: TripoSR is MIT, CLIP is MIT,
  Cap3D's captions are ODC-By and Objaverse's objects carry their own
  Creative Commons licences.

