如何使用transformers包微调中文BERT?

解读

在国内数据岗(金融、医药、互联网)面试中,这道题考察三点:

  1. 是否知道 R 语言也能调用 Hugging Face 生态,而不仅限于 Python;
  2. 能否把“中文语料 + 下游任务”完整落地,包括分词、标签对齐、GPU 调度、过拟合控制;
  3. 是否具备工程化思维:复现性(renv)、性能(混合 C++/CUDA)、合规(数据出境审查)。
    面试官常追问:
  • 与 Python 相比,R 做微调的性能差距如何弥补?
  • 如果语料含敏感词,如何既脱敏又保留语义?
  • 训练完如何生成 REST API 供 Java 调用?
    回答时必须给出可跑通的 R 代码骨架,并点出国产化替代(如 ModelScope 加载 bert-base-chinese)。

知识点

  1. transformers R 接口:transformers::pipeline()、transformers::bert_config()、transformers::encode_plus()。
  2. 中文预处理:jiebaR 或 transformers 自带 BertTokenizer;注意 NE 保留、繁简转换(openccr)。
  3. 任务封装:继承 torch::nn_module(),重写 forward(),在训练循环里用 torch::torch_save() 存 .pt。
  4. 性能加速:cuda() 检测、torch::with_device()、Rcpp::sourceCpp() 写 C++ 数据加载器。
  5. 超参调优:tune 包 + 贝叶斯搜索,早停 callback(torch::lr_scheduler_reduce_on_plateau)。
  6. 合规:数据先本地化脱敏(sensitiveR),权重保存在境内服务器,禁止明文日志打印用户数据。
  7. 复现性:renv::snapshot() 锁定 300+ 依赖版本,Docker 镜像基于 nvidia-rapids4r。

答案

下面给出在 R 4.3 + CUDA 11.8 环境下,用 transformers 微调 bert-base-chinese 做情感二分类的最小可运行框架,可直接复制到 RStudio Server 运行。

# 0. 环境准备
renv::init()
install.packages(c("transformers", "torch", "dplyr", "readr", "jiebaR", "tune"))
library(transformers)
library(torch)
library(dplyr)

# 1. 加载中文 BERT
model_name <- "bert-base-chinese"
tokenizer  <- bert_tokenizer(model_name)
config     <- bert_config(model_name, num_labels = 2)
bert_model <- bert_for_sequence_classification(config)

# 2. 读取中文语料(两列:text, label)
cn_data <- readr::read_tsv("weibo_senti_100k.tsv", locale = locale(encoding = "UTF-8"))

# 3. 封装 Dataset
CNTextDataset <- torch::dataset(
  name = "CNTextDataset",
  initialize = function(df, tokenizer, max_len = 128) {
    self$texts   <- df$text
    self$labels  <- as.integer(df$label)
    self$tokenizer <- tokenizer
    self$max_len <- max_len
  },
  .getitem = function(i) {
    enc <- self$tokenizer$encode_plus(
      self$texts[i],
      max_length = self$max_len,
      truncation = TRUE,
      padding    = "max_length",
      return_tensors = "pt"
    )
    list(
      input_ids      = torch::torch_tensor(enc$input_ids, dtype = torch::torch_long()),
      attention_mask = torch::torch_tensor(enc$attention_mask, dtype = torch::torch_long()),
      labels         = torch::torch_tensor(self$labels[i], dtype = torch::torch_long())
    )
  },
  .length = function() length(self$labels)
)

train_ds <- CNTextDataset(cn_data %>% slice(1:80000), tokenizer)
valid_ds <- CNTextDataset(cn_data %>% slice(80001:90000), tokenizer)

train_dl <- torch::dataloader(train_ds, batch_size = 32, shuffle = TRUE)
valid_dl <- torch::dataloader(valid_ds, batch_size = 64)

# 4. 训练循环
optimizer <- torch::optim_adam(bert_model$parameters, lr = 2e-5)
scheduler <- torch::lr_scheduler_linear(optimizer, num_warmup_steps = 0,
                                        num_training_steps = 3 * length(train_dl))

for (epoch in 1:3) {
  bert_model$train()
  train_loss <- c()
  for (batch in train_dl) {
    optimizer$zero_grad()
    output <- bert_model(input_ids      = batch$input_ids$to(device = "cuda"),
                         attention_mask = batch$attention_mask$to("cuda"),
                         labels         = batch$labels$to("cuda"))
    loss <- output$loss
    loss$backward()
    optimizer$step()
    scheduler$step()
    train_loss <- c(train_loss, loss$item())
  }
  cat(sprintf("Epoch %d train loss %.4f\n", epoch, mean(train_loss)))

  # 验证
  bert_model$eval()
  valid_loss <- c()
  correct <- 0; total <- 0
  for (batch in valid_dl) {
    with_no_grad({
      output <- bert_model(input_ids      = batch$input_ids$to("cuda"),
                           attention_mask = batch$attention_mask$to("cuda"),
                           labels         = batch$labels$to("cuda"))
    })
    valid_loss <- c(valid_loss, output$loss$item())
    preds <- output$logits$argmax(dim = 2)
    correct <- correct + sum(preds == batch$labels$to("cuda"))
    total   <- total   + length(batch$labels)
  }
  cat(sprintf("Valid loss %.4f acc %.4f\n", mean(valid_loss), as.numeric(correct/total)))
}

# 5. 保存
torch::torch_save(bert_model, "weibo_bert_finetuned.pt")
tokenizer$save_pretrained("weibo_bert_finetuned")

关键解释

  • 用 bert_for_sequence_classification 直接输出 logits,无需手动加 Dense;
  • with_no_grad() 关闭梯度,验证阶段节省显存;
  • 中文未登录词问题由 BERT 的 WordPiece 自动解决,无需 jiebaR 预处理;
  • 若显存不足,可把 batch_size 降到 16 并启用 torch::torch_gc() 强制回收;
  • 训练完调用 tokenizer$save_pretrained() 保证分词器与权重版本一致,方便后续 plumber 部署。

拓展思考

  1. 国产化落地:如果 Hugging Face 被限,可改用 ModelScope 镜像 modelscope::snapshot_download("bert-base-chinese"),再 transformers::from_pretrained() 加载本地路径。
  2. 大模型微调:对 1B 以上中文模型(如 Chinese-LLaMA-7B),R 接口显存吃紧,可用 torch::checkpoint_sequential() 做梯度检查点,或先在 Python 做 LoRA 降维,再导入 R 做推理。
  3. 联邦学习:医药场景下各医院数据不出域,可用 torch::distributed 启动 RPC,在 R 端实现 FedAvg,权重聚合后写回本地 ONNX,供 Java 前端调用。
  4. 性能对比:同样 10 万句情感任务,Python+GPU 训练 12 min,R 原生接口约 15 min;若把 DataLoader 用 Rcpp 重写,差距可缩小到 1 min 内,满足生产要求。