在文本分词器的基础上,GPT-4 也会将视觉输入(图像/视频)“分词”为图像标记,这些标记的数量将决定您的 API 调用成本。因此,了解分词器的工作原理(或者至少掌握如何使用代码预先计算标记数量)非常重要,以免您的 API 账单超出预期。
在本文中, 我们将:
可视化分词器的工作流程分为三个步骤:
首先,将图像进行缩放以确保宽度和高度都不超过 2048 像素。这一步将保持图像的纵横比不变。
接着,根据合适的缩放比例调整图像,使得其最短的一边正好为 768 像素。
在前两步骤调整的图像中计算可以放入的 512x512 的瓷砖块数。
最终,标记总数(截至本文撰写时)可以通过以下方式计算:
下面是一个 Python 代码片段,实现了上述分词步骤。
from math import ceil
def calculate_image_tokens(width: int, height: int):
# 步骤 1:缩放至适合 2048 x 2048 的方形内(保持纵横比)
if width > 2048 or height > 2048:
aspect_ratio = width / height
if aspect_ratio > 1:
width, height = 2048, int(2048 / aspect_ratio)
else:
width, height = int(2048 * aspect_ratio), 2048
# 步骤 2:缩放至使最短边达到 768 像素
if width >= height and height > 768:
width, height = int((768 / height) * width), 768
elif height > width and width > 768:
width, height = 768, int((768 / width) * height)
# 步骤 3:计算可放入的 512x512 小块数量
tiles_width = ceil(width / 512)
tiles_height = ceil(height / 512)
# 计算总标记数
total_tokens = 85 + 170 * (tiles_width * tiles_height)
return total_tokens
from PIL import Image
image = Image.open("/path/to/your/image.jpg")
calculate_image_tokens(*image.size)
以上就是 GPT-4 如何对图像进行分词的简短的可视化说明和代码实现。希望这能帮助您更好地理解这个过程。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。