lerobot VLA--SmolVLA代码的讲解

VIPlerobot VLA--SmolVLA代码的讲解
2.图像resize至正方形224x224,图像长宽比不变,其他区域用黑色补充,标记为mask=1,若占位图像(摄像头缺失),则 创建全-1像素的占位图像 标记为mask=0,image为[1, 3, 512, 512],img_mask为True,masks列表长度为2,img_masks为2,因为我这里两个相机。文本嵌入:通过embed_language_tokens() 被转换为嵌入表示,lang_emb 是语言的嵌入,包含了语言的语法和语义信息。1.像素值[0,1]->[-1,1]
开通可读全文 ·4k 人阅读
最低0.47元/天 解锁文章

1.数据预处理

首先看modeling_smolvla.py中forward函数:

def forward(self, batch: dict[str, Tensor], noise=None, time=None) -> dict[str, Tensor]:
        """Do a full training forward pass to compute the loss"""
        if self.config.adapt_to_pi_aloha:
            batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
            batch[ACTION] = self._pi_aloha_encode_actions_inv(batch[ACTION])
        batch = self.normalize_inputs(batch)
        
        batch = self.normalize_targets(batch)
       
        images, img_masks = self.prepare_images(batch)
        state = self.prepare_state(batch)
        lang_tokens, lang_masks = self.prepare_language(batch)
        
        actions = self.prepare_action(batch)
        actions_is_pad = batch.get("actions_id_pad")
        # print(f"---batch action33----={batch[ACTION]} | {batch[ACTION].shape} | {actions}")
        loss_dict = {}
        losses = self.model.forward(images, img_masks, lang_tokens, lang_masks, state, actions, noise, time)
        loss_dict["losses_after_forward"] = losses.clone()

        if actions_is_pad is not None:
            in_episode_bound = ~actions_is_pad
            losses = losses * in_episode_bound.unsqueeze(-1)
            loss_dict["losses_after_in_ep_bound"] = losses.clone()

        # Remove padding
        losses = losses[:, :, : self.config.max_action_dim]
        loss_dict["losses_after_rm_padding"] = losses.clone()

        
        # For backward pass
        loss = losses.mean()
        # For backward pass
        loss_dict["loss"] = loss.item()
        return loss, loss_dict

(1)这个函数首先归一化处理,

batch = self.normalize_inputs(batch)

batch = self.normalize_targets(batch)

训练的时候先设置为inf

mean = torch.ones(shape, dtype=torch.float32) * torch.inf

std = torch.ones(shape, dtype=torch.float32) * torch.inf

然后通过采集数据集中state、action的均值和方差。分别是输入数据、输出数据、反归一化值

self.normalize_inputs = Normalize(...) # 输入归一化

self.normalize_targets = Normalize(...) # 训练目标归一化

self.unnormalize_outputs = Unnormalize(...) # 输出反归一化

注意这里:如果训练过程中加载模型,上面均值和方差参数会被模型中的统计参数覆盖掉。

2.图像数据预处理

images, img_masks = self.prepare_images(batch)

这段主要代码功能为:

1.像素值[0,1]->[-1,1]

2.图像resize至正方形224x224,图像长宽比不变,其他区域用黑色补充,标记为mask=1,若占位图像(摄像头缺失),则 创建全-1像素的占位图像 标记为mask=0,image为[16, 3, 512, 512](B,C,H,W),这里的batch_size为16,图像大小为3*512*512,图像img_mask为True,masks列表长度为2,img_masks为2,因为我这里两个相机。这里是训练时候的长度大小。

整个代码如下:

def prepare_images(self, batch):
        """Apply SmolVLA preprocessing to the images, like resizing to 224x224 and padding to keep aspect ratio, and
        convert pixel range from [0.0, 1.0] to [-1.0, 1.0] as requested by SigLIP.
        """
        images = []
        img_masks = []
        present_img_keys = [key for key in self.config.image_features if key in batch]
        missing_img_keys = [key for key in self.config.image_features if key not in batch]

        
        if len(present_img_keys) == 0:
            raise ValueError(
                f"All image features are missing from the batch. At least one expected. (batch: {batch.keys()}) (image_features:{self.config.image_features})"
            )
        # Preprocess image features present in the batch# 调整大小并填充(保持宽高比)
        for key in present_img_keys:
            img = batch[key][:, -1, :, :, :] if batch[key].ndim == 5 else batch[key]
            if self.config.resize_imgs_with_padding is not None:
                img = resize_with_pad(img, *self.config.resize_imgs_with_padding, pad_value=0)

            # Normalize from range [0,1] to [-1,1] as expacted by siglip
            img = img * 2.0 - 1.0

            bsize = img.shape[0]
            device = img.device
            if f"{key}_padding_mask" in batch:
                mask = batch[f"{key}_padding_mask"].bool()
            else:
                mask = torch.ones(bsize, dtype=torch.bool, device=device)
            images.append(img)
            img_masks.append(mask)

        # Create image features not present in the batch
        # as fully 0 padded images.
        for num_empty_cameras in range(len(missing_img_keys)):
            if num_empty_cameras >= self.config.empty_cameras:
                break
            img = torch.ones_like(img) * -1
            mask = torch.zeros_like(mask)
            images.append(img)
            img_masks.append(mask)
        return images, img_masks

3.state数据预处理

state = self.prepare_state(batch)

这段代码主要将state的维数使用“0”从6维pad至32维,state:[16, 32]

 def prepare_state(self, batch):
        """Pad state"""
        state = batch[OBS_STATE][:, -1, :] if batch[OBS_STATE].ndim > 2 else batch[OBS_STATE]
        state = pad_vector(state, self.config.max_state_dim)
        return state

4.language数据预处理

lang_tokens, lang_masks = self.prepare_language(batch)、

用HuggingFaceTB/SmolVLM2-500M-Video-Instruct对task分词,task文本长度pad至48,lang_tokens为文本的token ID序列,lang_masks为对应的attention mask,用于标识哪些是有效token。我这里输入lang_tokens为[16, 10],lang_masks全为true,

注意:这里的长度10是根据提示词长度变化的,我输入的提示词为10,可以用下面代码测试你的长度。

for i, task in enumerate(tasks[:3]):  # 检查前3个
            test_tokens = self.language_tokenizer.encode(task)
            print(f"任务 {i} 的token长度: {len(test_tokens)}")
 def prepare_language(self, batch) -> tuple[Tensor, Tensor]:
        """Tokenize the text input"""
        device = batch[OBS_STATE].device
        tasks = batch["task"]
        if len(tasks) == 1:
            tasks = [tasks[0] for _ in range(batch[OBS_STATE].shape[0])]

        tasks = [task if task.endswith("\n") else f"{task}\n" for task in tasks]
        tokenized_prompt = self.language_tokenizer.__call__(
            tasks,
            padding=self.config.pad_language_to,
            padding_side="right",
            max_length=self.config.tokenizer_max_length,
            return_tensors="pt",
        )
        lang_tokens = tokenized_prompt["input_ids"].to(device=device)
        lang_masks = tokenized_prompt["attention_mask"].to(device=device, dtype=torch.bool)
        return lang_tokens, lang_masks

5.action数据预处理

actions = self.prepare_action(batch)

主要将action的维数扩充到32维,大小为(batch_size x sequence_length x features_dimension),大小为([16, 5, 32]

   def prepare_action(self, batch):
        """Pad action"""
        actions = pad_vector(batch[ACTION], self.config.max_action_dim)
        return actions

6.生成噪声

sample_noise(actions.shape, actions.device)

生成和actions size相同的高斯噪声

7.生成time

self.sample_time(actions.shape[0], actions.device)

time数值分布在[0.001,0.999]之间,控制噪声和action的混合比例,用于后续流匹配的训练

time接近1,输入接近噪音,反之接近原始actions

注意这里训练是由action到噪声

8.生成target

模型的主要思想为流匹配,模型拟合出噪声->动作(目前看来是动作->噪声反向拟合了)的运动趋势,即:

9.前缀嵌入

prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(

images, img_masks, lang_tokens, lang_masks, state=state

)

代码的流程是依次对输入图像、语言、机器状态进行分别做embedding,然后进行按列合并为一个前缀输入。

   

VIP 轻量SmolVLA:半层VLM、视觉压缩与异步推理赋能具身智能 SmolVLA是一种轻量级视觉-语言-行动策略,通过精简模型结构实现高效机器人控制。其核心设计包括:1)前端采用小型VLM(视觉SigLIP+语言SmolLM2)进行感知理解,仅使用中间层特征;2)视觉token压缩技术,将每帧token从1024降至64;3)动作专家采用交叉注意力与因果自注意力交替的三明治结构。这些设计使得模型参数量仅0.45B,比同类模型小10倍,同时保持性能。训练采用Flow Matching方法预测动作序列,推理时支持异步执行以降低延迟。该方案在低算力环境下展现出高效的多任务控制能 开通可读全文·2.4k 阅读·36 点赞·23 收藏 阅读全文

相关推荐

开源VLA解决方案SmolVLA

让机器人 AI 不再依赖昂贵硬件,极大降低了研究和应用门槛。模型,专为低成本、高效的机器人控制设计。上运行,同时保持与大型 VLA 模型相当的性能。

xuweilin的博客 1459

LeRobot SmolVLA:从训练到推理链路剖析

本文分析了SmolVLA策略的实现框架,重点探讨了其训练和推理机制。该策略通过SmolVLAPolicy、VLAFlowMatching和SmolVLMWithExpertModel三个核心类实现,采用flow matching机制进行训练。

laumy的学习笔记 1855

VS2015与QT界面开发中解决‘ui_xxx.h‘文件类名不一致导致的编译错误

本文详细解析了在VS2015与QT界面开发中,因.ui文件顶层部件objectName与生成类名不一致导致'ui_xxx.h'文件出现'不完整的类型'编译错误的根本原因。通过分步排查,指导开发者统一Qt设计师对象名、自动生成文件类名及代码引用名,并提供强制重新编译UI文件、清理中间文件等解决方案,有效解决此类常见编译问题。

weixin_29009339的博客 248

UDS诊断ISO14229新手入门篇

这个命令的格式稍微复杂一点。sub-function = 0x06 用于读取某个 DTC 及其相关的环境数据,此时 parameter 为 4 个 byte,前三个 byte 用于标识我们要读取的 DTC,第四个 byte 用于标识要读取的环境数据的范围,UDS 规定使用 FF 来表示读取所有的环境数据,各厂家可以要根据自己的需求定义其他的值来代表要读取的环境数据的范围。环境数据包括 DTC 状态,优先级,发生次数,老化计数器,时间戳,里程等,厂家还可以根据自己的需求定义一些此 DTC 产生时的测量数据。

weixin_45387165的博客 1980

全在这了!全国分省90米、30米、12.5米、5米DEM高程模型数据下载方式汇总

全在这了!全国分省90米、30米、12.5米、5米DEM高程模型数据下载方式汇总 SRTM15(450米)免费下载 https://pan.baidu.com/s/1eO0U6wfzs7YSe2EQdxRJ2Q提取码:o7am GMTED(250米)免费下载 https://pan.baidu.com/share/init?surl=nrbbdbhyNVQV46XwqzqLlg 提取码:V7X9 SRTM3 (90米)免费下载 https://pan.baidu.com/share/..

TuxinyunGIS的博客 1万+

如何实现C++动态调用动态链接库(DLL或SO)

使用函数指针来定义函数的类型,以便在动态库中找到的函数能够正确地调用。函数指针的类型必须与函数的签名(参数类型和返回类型)匹配。// 函数指针#ifdef _MSC_VER // Windows环境下的导出声明__declspec。

weixin_48438353的博客 7987

从零构建机械臂规划栈:Pinocchio、OMPL与Ruckig的工程化融合实践

本文详细介绍了如何从零构建机械臂规划栈,通过融合Pinocchio、OMPL和Ruckig三大核心组件,实现高性能的机械臂运动规划与轨迹生成。文章深入探讨了技术选型、工程架构设计及实战优化技巧,特别针对逆解、路径规划和轨迹平滑等关键环节提供了实用解决方案,适用于工业场景中的高实时性需求。

weixin_29072299的博客 434

MFC实现键盘钩子(附完整源码)

MFC实现键盘钩子(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 395

【异常检测】【EfficientAD】论文简单梳理与代码实现

EfficientAD作为较近的一篇异常检测网络,主要还是从S-T网络入手,对齐进行了相关改进。修改特征提取器引入自动编码器hard loss以及惩罚项。

胡侃有料的博客 2863

保姆级YOLOv8改进 | 基于DWRSeg扩张式残差机制的小目标检测优化(附修改后的C2f与Bottleneck模块)

DWRSeg机制:通过动态权重调整和扩张卷积有效提升了小目标的检测能力。C2f和Bottleneck模块修改:通过集成DWRSeg模块,增强了特征提取和残差学习能力。实验结果:在多个应用场景中,改进后的YOLOv8展现了更高的检测精度,特别是在小目标检测中表现突出。

一键难忘的博客 3221

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

上一篇: GraspNet机械臂抓取以及常用VLA数据集格式介绍
下一篇: 强化学习(RL)中数据采样存储与加载--TorchRL
Robert--cao
博客等级 码龄14年 3764粉丝 97原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Robert--cao

你的鼓励是前进的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址