You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

微调Falcon 40B时遇非矩形序列转Tensor错误求助

解决LLM微调TensorFlow数据集创建的非矩形序列错误

问题描述

在基于文本评论和标签列表创建LLM微调的TensorFlow数据集时,执行分词后调用tf.data.Dataset.from_tensor_slices()触发以下错误:

TypeError: Could not build a TypeSpec for [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ...] with type list 

During handling of the above exception, another exception occurred:

ValueError: Can't convert non-rectangular Python sequence to Tensor.

原因是分词后的token序列长度不一致,TensorFlow要求输入的特征必须是矩形结构(每个样本的特征维度相同),无法处理长度参差不齐的序列。

解决方案

核心是对分词后的序列进行统一padding,确保所有样本的token长度一致,具体步骤如下:

1. 修改分词代码,添加padding配置

调用tokenizer时,指定padding='max_length'和max_length参数,对短序列补全、长序列截断,保证所有序列长度统一:

model_name = "tiiuae/falcon-40b-instruct"

tokenizer = AutoTokenizer.from_pretrained(model_name)
# 配置分词参数,统一序列长度
tokenized_text = tokenizer(
    text_list,
    truncation=True,
    padding='max_length',
    max_length=512,  # 可根据模型支持的最大长度(Falcon-40b为2048)或数据情况调整
    return_tensors='tf'  # 可选,直接返回TensorFlow张量,简化后续处理
)

2. 创建TensorFlow数据集

此时tokenized_text中的input_ids、attention_mask等特征都是长度一致的结构,可直接用于创建数据集:

import tensorflow as tf

dataset = tf.data.Dataset.from_tensor_slices((dict(tokenized_text), labels_list))

3. 可选:动态计算最大序列长度

如果不想硬编码max_length,可以先统计所有文本的分词长度,再用最大值作为padding长度:

# 统计所有文本的分词长度
token_lengths = [len(tokenizer.encode(text)) for text in text_list]
max_len = max(token_lengths)

# 使用动态计算的max_len分词
tokenized_text = tokenizer(
    text_list,
    truncation=True,
    padding='max_length',
    max_length=max_len,
    return_tensors='tf'
)

额外说明

原代码仅设置了truncation=True(截断过长文本),但未处理过短文本的补全,导致输出的token序列长度不一致,形成非矩形数组,触发TensorFlow的转换错误。添加padding后,所有样本的特征维度统一,即可正常创建数据集。

内容的提问来源于stack exchange,提问作者Rahul Dhiman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 18:35:11