3D 生成模型微调权威指南
原题The Definitive Fine-Tuning Guide for 3D Generation Models
推荐理由TRELLIS.2 的 LoRA 指南按稀疏结构与几何阶段定向适配,并保留纹理模块,适合希望改善特定三维生成缺陷的实践者。
读前速览
本指南全面介绍如何使用 LoRA 适配器微调 3D 生成模型 TRELLIS.2,以改善鞋底几何等特定方面,并详细讲解如何通过 Hugging Face Jobs 和本地 Docker 部署完成操作。
TRELLIS.2 使用统一的潜在表示,通过五阶段流水线在不同 3D 格式之间转换
该流水线包含背景移除、使用 DINOv3 进行图像编码、稀疏结构生成、精细几何生成和材质生成。每个阶段都会生成中间表示,并将其传递给下一阶段。
LoRA 适配器有选择地应用于稀疏结构和形状 flow DiT 模型,以提高几何精度
文章说明,训练的适配器参数仅有 9.3 million(稀疏结构的秩为 8,形状 flow 的秩为 16),既能保留预训练模型的知识,也能针对鞋底几何实现特定任务的改进。
冻结纹理 flow DiT,避免因漫反射颜色图混合光照与表面属性而造成灾难性遗忘
由于数据集的漫反射贴图中包含烘焙后的光照效果,而非独立的材质贴图,训练纹理阶段会导致模型错误地将光照学成表面属性,从而削弱其通用能力。
完整的 Docker 容器支持基于云端的 Hugging Face Jobs 和本地微调工作流
两个容器镜像分别负责预处理(使用 Blender 渲染 16 个视角)和训练,并针对两种部署方式提供详细的命令行操作说明,让使用不同硬件配置的用户都能轻松进行微调。
完整摘要
本文提供了一份使用 LoRA(低秩适配)技术微调热门 3D 生成模型 TRELLIS.2 的权威指南。文章介绍了该模型如何通过五阶段流水线,根据输入图像生成 3D 对象,涵盖背景移除、图像编码、稀疏结构生成、几何生成和材质生成。指南重点讲解如何通过针对性 LoRA 适配器,分别应用于稀疏结构 flow DiT 和形状 flow DiT,冻结纹理 flow DiT,从而改善 3D 生成的特定方面。文章还详细介绍了如何使用 Blender 和 TRELLIS.2 预处理流水线处理数据,随后使用提供的 Docker 容器进行 LoRA 微调;这些容器既可在 Hugging Face Jobs 上运行,也可在本地运行。文章以 Google Scanned Objects 的鞋类数据集为例,展示如何提高特定类别物体(如鞋底)的几何精度。
目录 · 20 节
简而言之:在这篇博客中,我们提供了微调脚本和容器,帮助你使用自己的 3D 资产微调热门 3D 模型 TRELLIS.2,并且可以在本地和 Hugging Face Jobs 上运行。如果你想进行微调,只需设置少量参数(前提是你已将数据集更新到 Hugging Face Hub),就可以使用我们的脚本;也可以通过这个代码仓库自行调整。如果你想了解更多,我们会介绍脚本的工作原理。开始吧!TLDR; In this blog, we provide fine-tuning scripts and containers to fine-tune TRELLIS.2, a popular 3D model on your 3D assets, that can run both locally and on Hugging Face Jobs. If you are interested in fine-tuning, you can use our scripts with few arguments (assuming you updated your dataset to Hugging Face Hub) or tinker with them yourself with this repository. If you want to learn more, we go through how the script works. Let’s go!
简介 Introduction
3D 生成在机器人、仿真、媒体和娱乐领域有着广泛用途。在这些领域中,很难让生成的物体遵循严格的规则,也很难统一模型和数据的表示方式。文件格式有很多种,例如 GLB 和 PLY;表示形式也有很多种,例如神经辐射场(NeRF)和 3D 高斯泼溅(3DGS)。每种方式都有各自的优缺点。3D generation has many uses in robotics, simulation, media, and entertainment. In these fields, it is difficult to make generated objects obey strict rules and standardize model and data representations. There are many file formats, such as GLB and PLY. There are also many representations, such as neural radiance fields (NeRFs) and 3D Gaussian splatting (3DGS). Each one has different advantages and disadvantages.
TRELLIS 引入了一种通用的内部表示,称为统一潜在表示。其解码器会将这种表示转换为所需输出格式的 3D 模型。因此,你无需针对每种表示格式使用不同的模型。TRELLIS introduced a common internal representation, called a unified latent representation. Its decoders convert this representation into 3D models in the required output format. Thus, you do not have to use different models for each representation format.
同一团队随后发布了 TRELLIS.2,改进了模型对 3D 结构的表征。但这两个模型都没有提供一种简单的方法来针对特定任务进行适配。The same team then released TRELLIS.2, which improves the model's representation of 3D structure. But neither model gives an easy way to adapt it to a specific task.
我们希望改进的方面 What we want to improve
通用模型(如 TRELLIS.2)可能会在特定应用中至关重要的细节上出错。例如,用户可能需要准确的家具模型几何结构。如果没有针对该任务进行微调,预训练模型生成的几何结构可能不够准确。我们的实验使用了 GSO 中一个包含 188 个鞋类物体的子集。在初步测试中,预训练模型通常能生成外观正确的鞋子,但鞋底不准确。我们测试 LoRA 是否能提高鞋底的准确性。A general-purpose model, such as TRELLIS.2, can make errors in details that are important for a specific application. For example, a user may need accurate geometry for furniture models. Without fine-tuning for that task, the pretrained model can produce geometry that is insufficiently accurate. We use a subset of GSO that has 188 footwear objects for our experiment. In our initial tests, the pretrained model usually produced shoes that looked correct, but the soles were incorrect. We test whether a LoRA can make the soles more accurate.
我们的目标是使用 Google Scanned Objects (GSO) 数据集提升 TRELLIS.2 在特定物体类别上的性能。我们将说明训练期间需要微调哪些流水线组件,以及哪些组件应保持不变。该流水线将结构、精细几何形状和材质分开处理。因此,我们只会微调对任务至关重要的组件。Our goal is to use the Google Scanned Objects (GSO) dataset to improve the performance of TRELLIS.2 on a specific object category. We will explain which pipeline components to fine-tune and which to leave unchanged during training. The pipeline separates structure, detailed geometry, and materials. Thus, we will fine-tune only the components that are important for our task.
选择冻结哪些内容,与选择微调哪些内容同样重要。Choosing what to freeze matters as much as choosing what to fine-tune.
我们将使用什么? What will we use?
LoRA LoRA
LoRA 是 low-rank adaptation(低秩适配)的简称,它通过训练小型适配器矩阵来微调模型,同时冻结原始权重。这减少了可训练参数的数量,以及存储其梯度和优化器状态所需的内存。我们使用 Hugging Face 的 PEFT 库来添加并训练这些适配器。更多信息请阅读我们的 LoRA 指南。LoRA, short for low-rank adaptation, fine-tunes a model by training small adapter matrices while keeping the original weights frozen. This reduces the number of trainable parameters and the memory needed for their gradients and optimizer state. We use Hugging Face’s PEFT library to add and train these adapters. For more information, read our LoRA guide.
Hugging Face 作业 Hugging Face Jobs
Hugging Face Jobs 在云端硬件上运行容器化工作负载。我们用它进行预处理和训练。如果要改用自己的 GPU,请参阅下方的本地 Docker 命令。开始之前,请确保你已具备:Hugging Face Jobs runs containerized workloads on cloud hardware. We use it for preprocessing and for training. To use your own GPU instead, see the local Docker commands below. Before you start, make sure that you have:
- 可在此处获取的 HF_TOKENA HF_TOKEN that you can obtain from here
- 你的 Hugging Face 账户必须拥有 DINOv3 的访问权限,因为 DINOv3 是一个受限模型。Your Hugging Face account must have access to DINOv3, because DINOv3 is a gated model
- 如果使用自己的数据集,请在开始前将其网格上传到 Hub。If you use your own dataset, upload its meshes to the Hub before you start.
TRELLIS.2 的工作原理 How TRELLIS.2 works
在开始训练之前,我们先来看看 TRELLIS.2 如何生成 3D 对象,以及我们会在哪里添加 LoRA 适配器。Before we train, let’s look at how TRELLIS.2 generates a 3D object and where we’ll add LoRA adapters.
TRELLIS.2 分为五个主要阶段:移除图像背景、对图像进行编码、预测粗略结构、生成精细几何形状,以及生成材质。随后,整个流程会将结果导出为带纹理的网格。TRELLIS.2 has five main stages: remove the image background, encode the image, predict the coarse structure, generate detailed geometry, and generate materials. The pipeline then exports the result as a textured mesh.
对输入图像进行编码 Encoding the input image
首先,BiRefNet 会从输入图像中移除背景。随后,DINOv3-L 将图像编码为特征令牌。生成模型利用这些令牌来引导 3D 对象的生成。First, BiRefNet removes the background from the input image. DINOv3-L then encodes the image into feature tokens. The generation models use these tokens to guide the 3D object.
稀疏结构生成(稀疏结构流) Sparse Structure Generation (Sparse Structure Flow)
The sparse-structure flow DiT predicts the object's coarse shape. It is a diffusion transformer (DiT) that makes a small latent of size 16³ × 8. A variational autoencoder (VAE) decoder then changes this latent into a 64 × 64 × 64 occupancy grid. Each voxel in the grid shows if that location is part of the object. A voxel is a pixel in three dimensions. We add LoRA adapters to this model because its output guides the geometry stage.

O-Voxel 与结构化潜变量 O-Voxel and Structured Latents
O-Voxel 是 TRELLIS.2 的 3D 格式。它是一种稀疏体素网格,只保留物体表面上的体素。每个体素都保存局部几何信息(例如网格顶点)和材质属性。由于这种格式体积小,CPU 可以在几秒内将网格转换为 O-Voxel,GPU 也可以在几秒内将 O-Voxel 转换回网格。O-Voxel is the 3D format of TRELLIS.2. It is a sparse voxel grid. It keeps only the voxels on the object's surface. Each voxel keeps local geometry, such as a mesh vertex, and material attributes. Because the format is small, a CPU changes a mesh into O-Voxel in seconds. A GPU changes O-Voxel back into a mesh in seconds.
Structured sparse latents come from TRELLIS. They keep 3D data in sparse tensors, which makes computation faster. The model uses only approximately 10% of the voxels in the grid, so it does not spend compute on empty voxels. Thus, the shape flow DiT and the texture flow DiT are sparse transformers. The sparse-structure flow DiT is a dense transformer.

几何生成(形状流) Geometry Generation (Shape Flow)
Shape Flow DiT 使用占据网格和 DINOv3 特征 token 生成一个潜在表示。随后,另一个 VAE 解码器将该潜在表示转换为分辨率为 512 × 512 × 512 的 O-Voxel 几何体。The shape flow DiT uses the occupancy grid and the DINOv3 feature tokens to make a latent. Another VAE decoder then changes this latent into O-Voxel geometry at a resolution of 512 × 512 × 512.
我们在这个阶段为 DiT 添加 LoRA 适配器,因为它负责控制物体的形状。We add LoRA adapters to the DiT at this stage because it controls the object's shape.
材质生成 + 网格创建 Material Generation + Mesh Creation
在最后一个阶段,纹理流 DiT 将形状潜变量和 DINOv3 特征作为输入,用于定义几何表面的材质和纹理。随后,VAE 解码器会将潜变量转换为每个体素的基础颜色、金属度、粗糙度和 Alpha 值。我们不会在这个阶段添加 LoRA 适配器。我们的数据集包含漫反射颜色贴图,但缺少该阶段训练所需的独立材质贴图。此外,我们的问题在于鞋子的形状,而基础模型已经能够生成不错的颜色和纹理。In the last stage, the texture flow DiT uses the shape latent and the DINOv3 features as input. It defines the materials and textures of the geometry's surface. A VAE decoder then changes the latent into base color, metallic, roughness, and alpha values for each voxel. We do not add LoRA adapters to this stage. Our dataset has diffuse color maps, but it lacks the separate material maps this stage needs for training. Also, our problem is the shoe's shape. The base model already makes good colors and textures.
最后,管线将几何属性和材质属性合并为带纹理的网格,并将其导出为 GLB 文件。Finally, the pipeline combines the geometry and material attributes into a textured mesh and exports it as a GLB file.
规划 Planning
需要微调哪些组件 Which components to fine-tune
我们只在稀疏结构流 DiT 和形状流 DiT 中添加 LoRA 适配器。这些 DiT 控制物体的形状和几何结构。我们冻结纹理流 DiT,以保留其当前能力。We add LoRA adapters only to the sparse-structure flow DiT and the shape flow DiT. These DiTs control the object's shape and geometry. We freeze the texture flow DiT to keep its current capabilities.
我们的数据集包含带有烘焙光照效果的漫反射颜色贴图。为了训练纹理流 DiT,我们需要单独的材质贴图。数据集中的颜色贴图将表面颜色与光照混在一起,因此不适合作为此次训练的目标。Our dataset contains diffuse color maps that include baked lighting effects. To train the texture flow DiT, we need separate material maps. The color maps in our dataset mix surface color with lighting. Thus, they are not correct targets for this training.
如果我们用这些贴图训练 texture flow DiT,它就能学会将光照表现为一种表面属性。它也可能忘记之前学到的内容,这个问题称为灾难性遗忘。If we train the texture flow DiT on these maps, it can learn to show lighting as a surface property. It can also forget what it learned before, a problem called catastrophic forgetting.
为什么使用 LoRA Why use LoRA
我们的子集从 GSO 的 1,030 个物体中选取了 188 双鞋。对于这么小的数据集,LoRA 比全量微调更合适。全量微调的成本高得多,也可能覆盖模型原本擅长的能力(即其学到的先验)。我们的配置为两个目标 DiT 总共训练约 930 万个适配器参数。对于稀疏结构流 DiT,我们在注意力层和前馈(MLP)层中使用秩为 8 的适配器;对于形状流 DiT,我们在注意力层中使用秩为 16 的适配器。秩决定了适配器矩阵的大小。秩越高,适配器可学习的内容就越多。Our subset has 188 shoes from the 1,030 objects in GSO. For a dataset this small, LoRA is a better choice than full fine-tuning. Full fine-tuning costs much more. It can also overwrite what the model already does well (its learned priors). Our configuration trains approximately 9.3 million adapter parameters in total for both targeted DiTs. We use rank 8 adapters in the attention and feed-forward (MLP) layers of the sparse-structure flow DiT. We use rank 16 adapters in the attention layers of the shape flow DiT. The rank sets the size of the adapter matrices. A higher rank lets the adapter learn more.
你将运行的内容 What you’ll run
3D 模型的设置可能需要许多依赖项和安装步骤。我们提供了两个 Docker 镜像(可在 Jobs 上或自己的机器上运行),其中包含所需的软件。一个镜像用于预处理,另一个用于微调。A 3D model setup can need many dependencies and installation steps. We supply two Docker images (that you can run on Jobs or your own machine) with the necessary software. One image is for preprocessing, and one is for fine-tuning.
训练 LoRA 适配器并将其上传到 Hub:To train your LoRA adapters and upload them to the Hub:
- 允许容器访问你的数据。Give the containers access to your data.
- 设置任务参数。Set the parameters for your task.
- 运行预处理容器。Run the preprocessing container.
- 运行微调容器。Run the fine-tuning container.
然后我们将介绍微调脚本及其设置,并说明每项设置如何影响训练。Then we explain the fine-tuning script, its settings, and how each setting affects training.
实验概述 Experiment overview
我们将分三个部分介绍这项实验:We’ll walk through three parts of the experiment:
- 准备数据。将 GLB 或 OBJ 网格转换为 TRELLIS.2 用于训练的潜在表示,并渲染输入图像。Prepare the data. Convert GLB or OBJ meshes into the latent representations TRELLIS.2 uses for training, and render the input images.
- 训练适配器。针对每个 DiT,使用准备好的数据集和 LoRA 配置运行一个作业。Train the adapters. Run one job for each DiT, with the prepared dataset and a LoRA configuration.
- 解释代码。检查容器如何加载数据、添加适配器并训练模型。Explain the code. Examine how the containers load the data, add adapters, and train the models.
我们保存预处理后的数据集,以便所有训练运行都能重复使用。We save the preprocessed dataset so that all training runs can reuse it.
操作指南 Walkthrough
在 Hugging Face Jobs 上运行 Running on Hugging Face Jobs
预处理 Preprocessing
预处理容器使用 Blender 为每个物体渲染 16 个视图。LoRA 训练将使用这些视图作为条件图像。Blender 通过 xvfb-run 工具在无显示环境下运行。容器还会对每个物体执行预处理流水线。请参阅此处的鞋类数据集,查看中间输出示例。对于我们的 188 个物体,在 a100-large 作业上完整运行耗时约 1 小时。此配套代码仓库还提供了一个精简版预处理流水线。The preprocessing container uses Blender to render 16 views of each object. LoRA training will use these views as conditioning images. Blender runs without a display, through the xvfb-run utility. The container also processes each object through the preprocessing pipeline. See the footwear dataset here for an example intermediate output. For our 188 objects, the full run took approximately 1 hour on an a100-large job. A compact version of the preprocessing pipeline is also available in this companion repository.
export HF_TOKEN=hf_xxx
# Replace your-username with your Hugging Face username
hf jobs run -d --flavor a100-large --timeout 6h --secrets HF_TOKEN \
cr.hf.co/suvadityamuk/trellis2-finetuning-prep:latest \
trellis2-prep \
--meshes your-username/my-meshes \
--push-to your-username/my-meshes-trellis2 \
--private --holdout 0.05 \
--views 16 --workers 8
对于 Hugging Face Jobs,我们会传入以下参数:For Hugging Face Jobs, we pass the following arguments:
| flag | meaning |
|---|---|
-d |
Detach: print the job ID and URL, then return. To follow the job, run hf jobs logs -f <id> |
--flavor a100-large |
The hardware. We use a100-large (80 GB). To see all options, run hf jobs hardware |
--timeout 6h |
The job stops after this time. Both commands resume. Preprocessing skips finished objects. Training continues from the newest checkpoint in --push-to |
--secrets HF_TOKEN |
Send your token (from HF_TOKEN or hf auth login) to the job as an encrypted environment variable. The token is not written into the image |
cr.hf.co/...:latest |
The image to run. All text after it is the command that runs in the container |
这个容器还接受一些其他参数(无论是在 Hugging Face Jobs 上运行还是通过 Docker 运行),相关说明请参见此处。预处理流水线中的各个步骤将在本节后文介绍。This container accepts a few more arguments (regardless of being run on Hugging Face Jobs or with Docker), that you can find documented over here. The steps taken in the preprocessing pipeline are documented in this section later.
LoRA 微调 LoRA Fine-tuning
训练容器会加载准备好的数据集以及配置预设或配置文件。它会使用 Trackio 记录训练指标。使用 Trackio 仪表板监控训练过程。The training container loads the prepared dataset and a configuration preset or file. It records training metrics with Trackio. Use the Trackio dashboard to monitor the run.
我们使用“ss”和“shape”来表示训练 LoRA 的两种模式。“ss”模式仅微调 Sparse-Structure Flow DiT,而“shape”模式则微调 Shape Flow DiT。在底层实现中,它们只是分别引用不同阶段所使用的 config.json 文件。稍后本节会详细介绍这一流程。We use ‘ss’ and ‘shape’ to indicate the two modes we have for training the LoRAs. The ‘ss’ mode will finetune only the Sparse-Structure Flow DiT, whereas the ‘shape’ mode will finetune the Shape Flow DiT. Under the hood, they simply reference different config.json files to use for each stage. More details about the process is available in this section later.
export HF_TOKEN=hf_xxx # Replace your-username with your Hugging Face username
hf jobs run -d --flavor a100-large --timeout 12h --secrets HF_TOKEN \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train --config ss \
--latents your-username/my-meshes-trellis2 \
--push-to your-username/my-trellis2-lora \
--run-name ss_lora \
--push-path ss_lora \
--trackio-space your-username/trellis2-trackio
hf jobs run -d --flavor a100-large --timeout 12h --secrets HF_TOKEN \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train --config shape \
--latents your-username/my-meshes-trellis2 \
--push-to your-username/my-trellis2-lora \
--run-name shape_lora \
--push-path shape_lora \
--trackio-space your-username/trellis2-trackio \
--set max_steps=3000 i_save=500
如果设置了 --push-to,容器会将适配器检查点上传到 Hub。容器接受的参数也在此处列出,以便简要查阅。同一代码库中还提供了一个精简脚本。If you set --push-to, the container uploads adapter checkpoints to the Hub. The container accepts parameters that are also documented here for brevity. A compact script is also available in the same repository.
如果你想用我们已经处理好的数据集进行尝试和微调,请随意使用以下命令。If you want to play around and fine-tune with the already-processed dataset we have, feel free to use the following set of commands.
export HF_TOKEN=hf_xxx
# Replace your-username with your Hugging Face username
# For the Sparse-Structure Flow DiT
hf jobs run -d --flavor a100-large --timeout 12h --secrets HF_TOKEN \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train \
--config ss \
--latents suvadityamuk/gso-footwear-trellis2-latents \
--push-to your-username/trellis2-footwear-lora \
--run-name ss_lora \
--push-path ss_lora \
--trackio-space your-username/trellis2-trackio \
--set max_steps=3000 i_save=500
# For the Shape Flow DiT
hf jobs run -d --flavor a100-large --timeout 12h --secrets HF_TOKEN \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train \
--config shape \
--latents suvadityamuk/gso-footwear-trellis2-latents \
--push-to your-username/trellis2-footwear-lora \
--run-name shape_lora \
--push-path shape_lora \
--trackio-space your-username/trellis2-trackio \
--set max_steps=3000 i_save=500
使用 Docker 在本地运行 Running locally with Docker
Preprocessing
命令和标志与 Hugging Face Jobs 相同,只有 Docker 选项不同。The commands and flags are the same as for Hugging Face Jobs. Only the Docker options are different.
# For preprocessing into latents
docker run --gpus all --rm --shm-size 16g -e HF_TOKEN=hf_xxx \
-v hf-cache:/root/.cache/huggingface -v "$PWD/work":/workspace/work \
cr.hf.co/suvadityamuk/trellis2-finetuning-prep:latest \
trellis2-prep --meshes your-username/my-meshes --push-to your-username/my-meshes-trellis2
LoRA Fine-tuning
# For Sparse-structure Flow DiT
docker run --gpus all --rm --shm-size 16g \
-v hf-cache:/root/.cache/huggingface -v "$PWD/work":/workspace/work \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train --config ss --latents your-username/my-meshes-trellis2 \
--push-to your-username/my-trellis2-lora --trackio-space your-username/trellis2-trackio
# For Shape Flow DiT
docker run --gpus all --rm --shm-size 16g \
-v hf-cache:/root/.cache/huggingface -v "$PWD/work":/workspace/work \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train --config shape --latents your-username/my-meshes-trellis2 \
--push-to your-username/my-trellis2-lora --trackio-space your-username/trellis2-trackio
如果你想在自己选择的机器上本地使用我们已经预处理好的数据集,请使用以下命令:If you want to use our already-preprocessed dataset locally on your machine of choice, use the following commands:
export HF_TOKEN=hf_xxx # Replace your-username with your Hugging Face username
# For Sparse-structure Flow DiT
docker run --gpus all --rm --shm-size 16g -e HF_TOKEN \
-v hf-cache:/root/.cache/huggingface \
-v "$PWD/work":/workspace/work \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train \
--config ss \
--latents suvadityamuk/gso-footwear-trellis2-latents \
--push-to your-username/trellis2-footwear-lora \
--trackio-space your-username/trellis2-trackio \
--set max_steps=3000 i_save=500
# For Shape Flow DiT
docker run --gpus all --rm --shm-size 16g -e HF_TOKEN \
-v hf-cache:/root/.cache/huggingface \
-v "$PWD/work":/workspace/work \
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \
trellis2-train \
--config shape \
--latents suvadityamuk/gso-footwear-trellis2-latents \
--push-to your-username/trellis2-footwear-lora \
--trackio-space your-username/trellis2-trackio \
--set max_steps=3000 i_save=500
我们训练好的 LoRA 适配器位于此代码库中:suvadityamuk/trellis-2-finetune-gsoOur trained LoRA adapters are in this repository: suvadityamuk/trellis-2-finetune-gso
在训练流水线内部 Inside the training pipeline
预处理为潜变量 Preprocessing into latents
We use TRELLIS.2’s frozen encoders to convert the input meshes into training latents. We save these latents, so later runs do not have to encode the meshes again.
我们还会在 Blender 中为每个物体渲染 16 个视图。训练时,我们会为每个样本随机选取一个视图作为条件图像。我们将 188 个物体中的 9 个留作评估,其余 179 个用于训练。这些留出的物体可以用于检验适配器能否处理模型在训练期间未见过的物体。We also render 16 views of each object in Blender. During training, we select one random view for each sample as the conditioning image. We keep 9 of the 188 objects for evaluation and train on the other 179. These held-out objects show whether the adapters work on objects unseen by the model during training.
Blender 为一个对象渲染出的部分视图Some of the views that Blender rendered for one object
第一段代码用于设置数据。FLOW 选择要训练的 flow DiT(ss 或 shape),STEPS 设置优化器步数。批量大小为 4,梯度累积步数为 4,因此有效批量大小为 16。然后,这段代码会加载所选 flow DiT 的 LoRA 配置文件,按照 TRELLIS.2 格式创建数据集,移除留出的对象,并创建用于微调的数据加载器。The first snippet sets up the data. FLOW selects the flow DiT to train (ss or shape), and STEPS sets the number of optimizer steps. A batch size of 4 with 4 gradient accumulation steps gives an effective batch size of 16. Then, the snippet loads the LoRA config file for the selected flow DiT, makes the dataset in the TRELLIS.2 format, removes the held-out objects, and makes the data loader for fine-tuning.
cfg = json.load(
open(
{
"ss": "/workspace/TRELLIS.2/configs/lora/ss_flow_lora_gso.json",
"shape": "/workspace/TRELLIS.2/configs/lora/slat_flow_img2shape_lora_gso.json",
}[FLOW]
)
)
key, latents = {
"ss": ("ss_latent", "ss_latents/ss_enc_conv3d_16l8_fp16_64"),
"shape": ("shape_latent", "shape_latents/shape_enc_next_dc_f16c32_fp16_512"),
}[FLOW]
roots = json.dumps(
{
"gso": {
key: f"{DATA}/{latents}",
"render_cond": f"{DATA}/renders_cond",
"meta": DATA,
}
}
)
ds = getattr(datasets, cfg["dataset"])(roots, **cfg["dataset_args"])
holdout = set(open(f"{DATA}/holdout.txt").read().split())
ds.instances = [(root, sha) for root, sha in ds.instances if sha not in holdout]
batches = cycle(
DataLoader(
ds,
batch_size=BATCH,
shuffle=True,
drop_last=True,
num_workers=4,
collate_fn=getattr(ds, "collate_fn", None),
)
)
准备 LoRA 适配器 Preparing LoRA adapters
We use the peft library to insert LoRA adapters into the selected layers. TRELLIS.2 has a custom forward pass, so the standard PeftModel() wrapper does not work. Instead, we call inject_adapter_in_model(). This function adds the adapters directly to the model and keeps its custom interface.
我们将可训练的适配器权重保持为 32 位浮点数(fp32),以确保数值稳定性,并在前向传播中使用 bfloat16(bf16)自动混合精度。自动混合精度允许 PyTorch 对某些操作使用较低精度,从而减少内存占用。自动混合精度不会改变冻结的骨干网络权重的存储方式。We keep the trainable adapter weights in 32-bit floating point (fp32) for numerical stability and use bfloat16 (bf16) autocasting for the forward pass. Autocasting lets PyTorch use lower precision for some operations, which decreases memory use. Autocasting does not change how the frozen backbone weights are stored.
model = models.from_pretrained(cfg["ckpt"])
for block in model.blocks:
block.use_checkpoint = True
inject_adapter_in_model(
LoraConfig(
r=cfg["rank"], lora_alpha=cfg["alpha"], target_modules=cfg["lora_targets"]
),
model,
)
params = []
for name, p in model.named_parameters():
p.requires_grad_("lora_" in name)
if p.requires_grad:
p.data = p.data.float() # fp32 master weights for LoRA
params.append(p)
model.cuda().train()
培训 Training
It’s important to note that our objective function here is good-old rectified flow matching (as seen in popular image-generation models like Stable Diffusion 3, Flux 2, and others). TRELLIS.2 used the same objective in pretraining, so it is a good choice for fine-tuning. For the theory, read this blog about flow matching.
我们仅更新稀疏结构和形状 DiT 中的 LoRA 参数。所有原始模型权重均保持冻结。We update only the LoRA parameters in the sparse-structure and shape DiTs. All original model weights remain frozen.
下面的代码片段展示了一个阶段的核心训练循环。它们比容器代码更简单,也未包含某些设置步骤。要了解完整工作流,请使用容器命令。The snippets below show the core training loop for one stage. They are simpler than the container code and do not include some setup steps. For the full workflow, use the container commands.
我们初始化优化器并加载 DINOv3,以提取输入图像的特征。We initialize the optimizer and load DINOv3 to extract features from the input images.
opt = torch.optim.AdamW(
params, lr=cfg["lr"], weight_decay=cfg["weight_decay"], betas=(0.9, 0.95)
)
dino = DinoV3FeatureExtractor(
cfg["image_cond_model"], image_size=cfg["image_size"]
).cuda()
然后我们在训练循环中执行以下步骤:We then follow these steps within the training loop:
- 为每个样本采样一个时间步 t(根据 TRELLIS.2 配置,稀疏结构流 DiT 使用 logitNormal,形状流 DiT 使用 uniform)。Sample a timestep t for each sample (using logitNormal for the sparse-structure flow DiT and uniform for the shape flow DiT based on the TRELLIS.2 config).
- 生成与数据形状匹配的随机噪声,并重塑 t 以进行广播。Generate random noise matching the data shape and reshape t for broadcasting.
- 根据 t 混合干净数据与噪声(其中 t = 0 表示噪声最少的数据,t = 1 表示纯噪声)。Mix clean data with noise based on t (where t = 0 is data with minimal noise, and t = 1 is pure noise).
- 在 t × 1000 处预测速度,以匹配预训练条件。Predict velocity at t × 1000 to match pretraining conditions.
- 将损失计算为预测速度与目标速度(x_t 的一阶导数)之间的均方误差。Calculate loss as the mean squared error between the predicted velocity and target velocity (the first derivative of x_t).
def flow_loss(x0, cond):
s = cfg["t_schedule"]
t = (
torch.rand(x0.shape[0])
if s["name"] == "uniform"
else torch.sigmoid(
torch.randn(x0.shape[0]) * s["args"]["std"] + s["args"]["mean"]
)
)
t = t.cuda()
noise = (
x0.replace(torch.randn_like(x0.feats))
if cfg["sparse"]
else torch.randn_like(x0)
)
tv = t.view(-1, *[1] * (len(x0.shape) - 1))
x_t = (1 - tv) * x0 + (cfg["sigma_min"] + (1 - cfg["sigma_min"]) * tv) * noise
pred, target = model(x_t, t * 1000, cond), (1 - cfg["sigma_min"]) * noise - x0
return (
F.mse_loss(pred.feats, target.feats)
if cfg["sparse"]
else F.mse_loss(pred, target)
)
训练循环计算损失并更新适配器权重。梯度累积会先累加 4 个小批次产生的梯度,再执行一次优化器更新。梯度检查点通过在反向传播过程中重新计算部分中间值来节省 GPU 内存。外层循环按指定的优化器步数运行,而内层循环则在一组批次上累积梯度。The training loop computes the loss and updates the adapter weights. Gradient accumulation adds the gradients from 4 small batches before each optimizer step. Gradient checkpointing saves GPU memory by recomputing some intermediate values during backpropagation. The outer loop runs for a given number of optimizer steps, whereas the inner loop accumulates gradients over a set of batches.
对于每个批次,DINOv3 都会对条件图像进行编码。在分类器自由引导(CFG)丢弃过程中,循环会将随机比例(p_uncond)的样本的条件设为零。接着,它使用 bf16 自动混合精度计算流匹配损失。内层循环结束后,它会裁剪梯度以防止更新幅度过大,并执行一次优化器步骤。它每 10 步记录一次损失,每 500 步保存一次适配器检查点。For each batch, DINOv3 encodes the conditioning image. For classifier-free guidance (CFG) dropout, the loop sets the conditioning to zero for a random fraction (p_uncond) of the samples. Then, it calculates the flow-matching loss with bf16 autocasting. After the inner loop, it clips the gradients to prevent very large updates and does an optimizer step. It logs the loss every 10 steps and saves an adapter checkpoint every 500 steps.
for step in range(1, STEPS + 1):
for _ in range(ACCUM):
batch = next(batches)
x0 = recursive_to_device(batch["x_0"], "cuda")
with torch.no_grad():
cond = dino(batch["cond"])
cond[torch.rand(len(cond), device="cuda") < cfg["p_uncond"]] = 0
with torch.autocast("cuda", dtype=torch.bfloat16):
loss = flow_loss(x0, cond) / ACCUM
loss.backward()
torch.nn.utils.clip_grad_norm_(params, cfg["grad_clip"])
opt.step()
opt.zero_grad()
结果 Results
我们训练了两个适配器:一个用于稀疏结构 DiT,另一个用于形状 DiT。容器镜像中的 LoRA 配置文件包含完整的训练设置:稀疏结构流 DiT 使用 ss_flow_lora_gso.json,形状流 DiT 使用 slat_flow_img2shape_lora_gso.json。每次训练都在 Hugging Face Jobs 上使用一张 A100 80 GB。稀疏结构训练耗时 7.2 小时,形状训练耗时 3.6 小时。We trained two adapters: one for the sparse-structure DiT and one for the shape DiT. The LoRA config files in the container image contain the full training settings: ss_flow_lora_gso.json for the sparse-structure flow DiT and slat_flow_img2shape_lora_gso.json for the shape flow DiT. Each run used one A100 80 GB on Hugging Face Jobs. The sparse-structure run took 7.2 hours, and the shape run took 3.6 hours.
The training loss of the sparse-structure flow DiT falls quickly at the start, then more slowly. The loss of the shape flow DiT stays at approximately the same level. These curves show how the training objective changes, but they do not directly measure the quality of the generated geometry.

流匹配损失会随采样的物体、噪声和时间步而变化。要判断微调是否改善了几何效果,我们还必须比较模型在留出物体上的输出。Flow-matching loss varies with the sampled objects, noise, and timesteps. To find out if fine-tuning improves the geometry, we must also compare outputs on the held-out objects.
下图比较了九个留出物体中的五个的输出结果。图中展示了输入图像、基础模型生成的输出、经过旋转调整后的基础输出、使用鞋类适配器得到的输出,以及参考扫描结果。在这些示例中,微调模型生成的鞋底与扫描结果更为接近。The figure below compares outputs for five of the nine held-out objects. It shows the input image, the base model’s generated output, the base output after a rotation adjustment, the output with the footwear adapters, and the reference scan. In these examples, the soles from the fine-tuned model are closer to the scans.
我们还使用三个指标来评估测试集上的几何结构:We also use three metrics to evaluate the geometry on the test set:
| Metric | What it means |
|---|---|
| Chamfer distance | The distance from points on one surface to the nearest points on the other surface, measured in both directions. Lower is better. |
| F-score @ 0.02 | The combination of precision (how much of the generated surface is near the reference) and recall (how much of the reference surface the generated surface covers). Here, the matching threshold is 2% of the scan’s bounding-box diagonal. Higher is better. |
| Normal consistency | How closely the surface directions agree. A surface normal is a vector perpendicular to the surface. Higher is better. |
In the chart’s nine-object comparison, the base model has a mean F-score of 0.276, compared with 0.803 for the model with the footwear adapters. Chamfer distance falls from 0.174 to 0.033, and normal consistency rises from 0.530 to 0.804. With both adapters, the F-score is better on all nine held-out objects.

所有运行的统计数据,请参见此 Trackio 空间。For the statistics of all runs, see this Trackio space.
未来方向 Future directions
呼,至此就完成了!我们通过为控制几何结构的两个模型组件添加 LoRA 适配器,对 TRELLIS.2 进行了鞋类生成微调。我们只准备了一次数据,在独立的任务中训练这些适配器,并在留出的物体上评估生成结果。Phew, so there we go! We fine-tuned TRELLIS.2 for footwear generation by adding LoRA adapters to the two model components that control geometry. We prepared the data once, trained the adapters in separate jobs, and evaluated the outputs on held-out objects.
主要的经验是,选择的训练目标应与问题以及你拥有的数据相符。在本实验中,我们对结构和形状阶段进行了微调,并冻结了纹理阶段。The main lesson is to select a training target that agrees with the problem and the data that you have. For this experiment, we fine-tuned the structure and shape stages and froze the texture stage.
接下来,我们可以考察相同的选择是否也有助于其他 3D 生成模型,例如 Pixal3D 和 UniLat3D。Next, we can examine if the same choices help other 3D generation models, such as Pixal3D and UniLat3D.
高斯泼溅和世界生成模型(例如 HunyuanWorld 2.0 和 NVIDIA Lyra 2.0)也可能是下一步的发展方向。它们的表示方式和训练流程可能需要采用不同的方法。Gaussian-splat and world-generation models, such as HunyuanWorld 2.0 and NVIDIA Lyra 2.0, are also possible next steps. Their representations and training pipelines can need different methods.
感谢你一路关注,我们下期再见!👋🤗Thank you for following along, and see you in the next one! 👋🤗









