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 Gemini API. 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 cho dịch vụ tạo văn bản của Gemini API.
Trước khi bắt đầu: Thiết lập dự án và khoá API của bạn
Trước khi gọi Gemini API, bạn cần thiết lập dự án và định cấu hình khoá API của mình.
Thiết lập
Thiết lập tính năng xác thực
Gemini API cho phép bạn điều chỉnh các mô hình bằng dữ liệu của riêng mình. Vì 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 khoá API.
Trước khi chạy hướng dẫn này, bạn cần thiết lập OAuth cho dự án của mình.
Cách dễ nhất để thiết lập trong Colab là sao chép nội dung của tệp client_secret.json
vào "Trình quản lý khoá 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) bằng tên khoá bí mật là CLIENT_SECRET
.
Lệnh gcloud này chuyển tệp client_secret.json
thành thông tin xác thực có thể dùng để xác thực 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 được điều chỉnh hiện có 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 xác định trực tiếp 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 vào phương thức.
Đối với ví dụ này, bạn sẽ điều chỉnh một mô hình để tạo số tiếp theo trong trình tự. Ví dụ: nếu đầu vào là 1
thì mô hình sẽ xuất ra 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 đượ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 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ờ quá trình đà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 cách sử dụng phương thức cancel()
. Huỷ nhận xét
dòng bên dưới và chạy ô chứa mã để huỷ công việc của bạn trước khi hoàn tất.
# operation.cancel()
Sau khi điều chỉnh xong, bạn có thể xem đường cong suy hao trong kết quả điều chỉnh. Đường cong mất cho biết mức độ sai lệch giữa các thông tin 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'>
Đánh giá mô hình
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ụ này đã được chấp nhận mặc dù có một số ví dụ hạn chế. Tuy nhiên, "tiếp theo" là một khái niệm tương đối đơn giản. Hãy xem 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ột mô hình. Nếu huỷ bất kỳ công việc điều chỉnh nào, bạn nên xoá các công việc đó vì hiệu suất của chúng có thể không dự đoán được.
genai.delete_tuned_model(f'tunedModels/{name}')
Mô hình 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.