# MatCha

## 概述

MatCha 是在论文 [MatCha: Enhancing Visual Language Pretraining with Math Reasoning and Chart Derendering](https://huggingface.co/papers/2212.09662) 中提出的，作者为 Fangyu Liu、Francesco Piccinno、Syrine Krichene、Chenxi Pang、Kenton Lee、Mandar Joshi、Yasemin Altun、Nigel Collier 和 Julian Martin Eisenschlos。

该论文的摘要指出：

*诸如图表、统计图和信息图之类的视觉语言数据在人类世界中无处不在。然而，最先进的视觉语言模型在这些数据上的表现并不理想。我们提出了 MatCha（数学推理与图表去渲染预训练），以增强视觉语言模型对图表/统计图与语言数据进行联合建模的能力。具体而言，我们提出了若干预训练任务，涵盖图表解构和数值推理，这两者是视觉语言建模中的关键能力。我们从最近提出的图像到文本视觉语言模型 Pix2Struct 出发，执行 MatCha 预训练。在 PlotQA 和 ChartQA 等标准基准上，MatCha 模型比最先进方法高出近 20%。我们还考察了 MatCha 预训练向截图、教科书插图和文档图表等领域迁移的效果，并观察到整体性能的提升，从而验证了 MatCha 预训练在更广泛的视觉语言任务中的实用性。*

## 模型描述

MatCha 是一个使用 `Pix2Struct` 架构训练的模型。您可以在 [Pix2Struct 文档](./pix2struct) 中了解有关 `Pix2Struct` 的更多信息。MatCha 是 `Pix2Struct` 架构的视觉问答子集。它会将输入问题渲染到图像上，并预测答案。

## 用法

目前 MatCha 共有 6 个检查点可用：

- `google/matcha`：基础 MatCha 模型，用于在下游任务上对 MatCha 进行微调
- `google/matcha-chartqa`：在 ChartQA 数据集上微调的 MatCha 模型。可用于回答有关图表的问题。
- `google/matcha-plotqa-v1`：在 PlotQA 数据集上微调的 MatCha 模型。可用于回答关于图表的问题。
- `google/matcha-plotqa-v2`：在 PlotQA 数据集上微调的 MatCha 模型。可用于回答关于图表的问题。
- `google/matcha-chart2text-statista`：在 Statista 数据集上微调的 MatCha 模型。
- `google/matcha-chart2text-pew`：在 Pew 数据集上微调的 MatCha 模型。

在 `chart2text-pew` 和 `chart2text-statista` 上微调的模型更适合摘要任务，而在 `plotqa` 和 `chartqa` 上微调的模型更适合问答任务。

您可以按以下方式使用这些模型（以 ChartQA 数据集为例）：

```python
import requests
from PIL import Image

from transformers import AutoProcessor, Pix2StructForConditionalGeneration

model = Pix2StructForConditionalGeneration.from_pretrained("google/matcha-chartqa").to(0, device_map="auto")
processor = AutoProcessor.from_pretrained("google/matcha-chartqa")
url = "https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/20294671002019.png"
image = Image.open(requests.get(url, stream=True).raw)

inputs = processor(images=image, text="Is the sum of all 4 places greater than Laos?", return_tensors="pt").to(0)
predictions = model.generate(**inputs, max_new_tokens=512)
print(processor.decode(predictions[0], skip_special_tokens=True))
```

## 微调

如需微调 MatCha，请参阅 pix2struct 的 [微调笔记本](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_pix2struct.ipynb)。对于 `Pix2Struct` 模型，我们发现使用 Adafactor 和余弦学习率调度器进行微调可以加快收敛速度：

```python
from transformers.optimization import Adafactor, get_cosine_schedule_with_warmup

optimizer = Adafactor(self.parameters(), scale_parameter=False, relative_step=False, lr=0.01, weight_decay=1e-05)
scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=1000, num_training_steps=40000)
```

MatCha 是一个使用 `Pix2Struct` 架构训练的模型。您可以在 [Pix2Struct 文档](./pix2struct) 中了解有关 `Pix2Struct` 的更多信息。

