API Gemini: Điều chỉnh mô hình bằng Python

Xem trên ai.google.dev Chạy trong Google Colab Xem nguồn trên GitHub

Trong sổ tay này, bạn sẽ tìm hiểu cách bắt đầu sử dụng dịch vụ điều chỉnh bằng cách sử dụng thư viện ứng dụng Python cho API Gemini. Tại đây, bạn sẽ tìm hiểu cách điều chỉnh mô hình văn bản dùng để hỗ trợ dịch vụ tạo văn bản của API Gemini.

Thiết lập

Xác thực

API Gemini cho phép bạn điều chỉnh mô hình trên dữ liệu của riêng mình. Vì đó là dữ liệu của bạn và các mô hình đã được điều chỉnh, nên cần kiểm soát quyền truy cập nghiêm ngặt hơn so với các Khoá API có thể cung cấp.

Để có thể chạy hướng dẫn này, bạn cần thiết lập OAuth cho dự án.

Trong Colab, cách thiết lập dễ dàng nhất là sao chép nội dung của tệp client_secret.json vào "Trình quản lý bí mật" của Colab (bên dưới biểu tượng khoá trong bảng điều khiển bên trái) dưới tên bí mật CLIENT_SECRET.

Lệnh gcloud này biến tệp client_secret.json thành thông tin xác thực có thể dùng để xác thực với dịch vụ.

import os
if 'COLAB_RELEASE_TAG' in os.environ:
  from google.colab import userdata
  import pathlib
  pathlib.Path('client_secret.json').write_text(userdata.get('CLIENT_SECRET'))

  # Use `--no-browser` in colab
  !gcloud auth application-default login --no-browser --client-id-file client_secret.json --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning'
else:
  !gcloud auth application-default login --client-id-file client_secret.json --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning'

Cài đặt thư viện ứng dụng

pip install -q google-generativeai

Nhập thư viện

import google.generativeai as genai

Bạn có thể kiểm tra các mô hình hiện đã được điều chỉnh bằng phương thức genai.list_tuned_model.

for i, m in zip(range(5), genai.list_tuned_models()):
  print(m.name)
tunedModels/my-model-8527
tunedModels/my-model-7092
tunedModels/my-model-2778
tunedModels/my-model-1298
tunedModels/my-model-3883

Tạo mô hình được điều chỉnh

Để tạo một mô hình được điều chỉnh, bạn cần truyền tập dữ liệu vào mô hình trong phương thức genai.create_tuned_model. Bạn có thể thực hiện việc này bằng cách trực tiếp xác định các giá trị đầu vào và đầu ra trong lệnh gọi hoặc nhập từ một tệp vào khung dữ liệu để truyền đến phương thức.

Trong ví dụ này, bạn sẽ điều chỉnh một mô hình để tạo ra số tiếp theo trong chuỗi. Ví dụ: nếu đầu vào là 1, mô hình sẽ xuất 2. Nếu dữ liệu đầu vào là one hundred, thì dữ liệu đầu ra phải là one hundred one.

base_model = [
    m for m in genai.list_models()
    if "createTunedModel" in m.supported_generation_methods][0]
base_model
Model(name='models/gemini-1.0-pro-001',
      base_model_id='',
      version='001',
      display_name='Gemini 1.0 Pro',
      description=('The best model for scaling across a wide range of tasks. This is a stable '
                   'model that supports tuning.'),
      input_token_limit=30720,
      output_token_limit=2048,
      supported_generation_methods=['generateContent', 'countTokens', 'createTunedModel'],
      temperature=0.9,
      top_p=1.0,
      top_k=1)
import random

name = f'generate-num-{random.randint(0,10000)}'
operation = genai.create_tuned_model(
    # You can use a tuned model here too. Set `source_model="tunedModels/..."`
    source_model=base_model.name,
    training_data=[
        {
             'text_input': '1',
             'output': '2',
        },{
             'text_input': '3',
             'output': '4',
        },{
             'text_input': '-3',
             'output': '-2',
        },{
             'text_input': 'twenty two',
             'output': 'twenty three',
        },{
             'text_input': 'two hundred',
             'output': 'two hundred one',
        },{
             'text_input': 'ninety nine',
             'output': 'one hundred',
        },{
             'text_input': '8',
             'output': '9',
        },{
             'text_input': '-98',
             'output': '-97',
        },{
             'text_input': '1,000',
             'output': '1,001',
        },{
             'text_input': '10,100,000',
             'output': '10,100,001',
        },{
             'text_input': 'thirteen',
             'output': 'fourteen',
        },{
             'text_input': 'eighty',
             'output': 'eighty one',
        },{
             'text_input': 'one',
             'output': 'two',
        },{
             'text_input': 'three',
             'output': 'four',
        },{
             'text_input': 'seven',
             'output': 'eight',
        }
    ],
    id = name,
    epoch_count = 100,
    batch_size=4,
    learning_rate=0.001,
)

Mô hình đã được điều chỉnh sẽ được thêm ngay vào danh sách mô hình đã được điều chỉnh nhưng trạng thái của mô hình đó sẽ được đặt thành "đang tạo" trong khi mô hình đó được điều chỉnh.

model = genai.get_tuned_model(f'tunedModels/{name}')

model
TunedModel(name='tunedModels/generate-num-2946',
           source_model='models/gemini-1.0-pro-001',
           base_model='models/gemini-1.0-pro-001',
           display_name='',
           description='',
           temperature=0.9,
           top_p=1.0,
           top_k=1,
           state=<State.CREATING: 1>,
           create_time=datetime.datetime(2024, 2, 21, 20, 4, 16, 448050, tzinfo=datetime.timezone.utc),
           update_time=datetime.datetime(2024, 2, 21, 20, 4, 16, 448050, tzinfo=datetime.timezone.utc),
           tuning_task=TuningTask(start_time=datetime.datetime(2024, 2, 21, 20, 4, 16, 890698, tzinfo=datetime.timezone.utc),
                                  complete_time=None,
                                  snapshots=[],
                                  hyperparameters=Hyperparameters(epoch_count=100,
                                                                  batch_size=4,
                                                                  learning_rate=0.001)))
model.state
<State.CREATING: 1>

Kiểm tra tiến trình điều chỉnh

Sử dụng metadata để kiểm tra trạng thái:

operation.metadata
total_steps: 375
tuned_model: "tunedModels/generate-num-2946"

Chờ khoá đào tạo kết thúc bằng cách sử dụng operation.result() hoặc operation.wait_bar()

import time

for status in operation.wait_bar():
  time.sleep(30)
0%|          | 0/375 [00:00<?, ?it/s]

Bạn có thể huỷ công việc điều chỉnh bất cứ lúc nào bằng phương thức cancel(). Huỷ nhận xét dòng bên dưới và chạy ô mã để huỷ công việc của bạn trước khi hoàn tất.

# operation.cancel()

Sau khi quá trình điều chỉnh hoàn tất, bạn có thể xem đường cong tín hiệu tổn hao trong kết quả điều chỉnh. Đường cong tổn thất cho thấy mức độ chênh lệch giữa các kết quả dự đoán của mô hình so với kết quả lý tưởng.

import pandas as pd
import seaborn as sns

model = operation.result()

snapshots = pd.DataFrame(model.tuning_task.snapshots)

sns.lineplot(data=snapshots, x = 'epoch', y='mean_loss')
<Axes: xlabel='epoch', ylabel='mean_loss'>

png

Đánh giá mô hình của bạn

Bạn có thể sử dụng phương thức genai.generate_text và chỉ định tên mô hình để kiểm thử hiệu suất của mô hình.

model = genai.GenerativeModel(model_name=f'tunedModels/{name}')
result = model.generate_content('55')
result.text
'56'
result = model.generate_content('123455')
result.text
'123456'
result = model.generate_content('four')
result.text
'five'
result = model.generate_content('quatre') # French 4
result.text                               # French 5 is "cinq"
'cinq'
result = model.generate_content('III')    # Roman numeral 3
result.text                               # Roman numeral 4 is IV
'IV'
result = model.generate_content('七')  # Japanese 7
result.text                            # Japanese 8 is 八!
'八'

Có vẻ như nhiệm vụ đó đã tiếp nhận nhiệm vụ mặc dù có ít ví dụ, nhưng "tiếp theo" là một khái niệm đơn giản, hãy xem phần hướng dẫn điều chỉnh để được hướng dẫn thêm về cách cải thiện hiệu suất.

Cập nhật nội dung mô tả

Bạn có thể cập nhật nội dung mô tả của mô hình được điều chỉnh bất cứ lúc nào bằng phương thức genai.update_tuned_model.

genai.update_tuned_model(f'tunedModels/{name}', {"description":"This is my model."});
model = genai.get_tuned_model(f'tunedModels/{name}')

model.description
'This is my model.'

Xoá mô hình

Bạn có thể dọn dẹp danh sách mô hình được điều chỉnh bằng cách xoá các mô hình bạn không cần nữa. Sử dụng phương thức genai.delete_tuned_model để xoá mô hình. Nếu đã huỷ bất kỳ lệnh điều chỉnh nào, bạn nên xoá các lệnh đó vì hiệu suất của chúng có thể khó dự đoán.

genai.delete_tuned_model(f'tunedModels/{name}')

Mô hình này không còn tồn tại:

try:
  m = genai.get_tuned_model(f'tunedModels/{name}')
  print(m)
except Exception as e:
  print(f"{type(e)}: {e}")
<class 'google.api_core.exceptions.NotFound'>: 404 Tuned model tunedModels/generate-num-2946 does not exist.