Instructions to use Indy1985/LoRA_template_unsloth_1_lora with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Indy1985/LoRA_template_unsloth_1_lora with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Indy1985/LoRA_template_unsloth_1_lora")# Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Indy1985/LoRA_template_unsloth_1_lora") model = AutoModelForCausalLM.from_pretrained("Indy1985/LoRA_template_unsloth_1_lora", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Indy1985/LoRA_template_unsloth_1_lora with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Indy1985/LoRA_template_unsloth_1_lora" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Indy1985/LoRA_template_unsloth_1_lora", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Indy1985/LoRA_template_unsloth_1_lora
- SGLang
How to use Indy1985/LoRA_template_unsloth_1_lora with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Indy1985/LoRA_template_unsloth_1_lora" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Indy1985/LoRA_template_unsloth_1_lora", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Indy1985/LoRA_template_unsloth_1_lora" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Indy1985/LoRA_template_unsloth_1_lora", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Indy1985/LoRA_template_unsloth_1_lora with Docker Model Runner:
docker model run hf.co/Indy1985/LoRA_template_unsloth_1_lora
- Model Card for Model ID
- Model Details
- Uses
- Bias, Risks, and Limitations
- How to Get Started with the Model
- Training Details
- Evaluation
- Model Examination [optional]
- Environmental Impact
- Technical Specifications [optional]
- Citation [optional]
- Glossary [optional]
- More Information [optional]
- Model Card Authors [optional]
- Model Card Contact
- Sample Use
Model Card for Model ID
Model Details
Model Description
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
- Developed by: [More Information Needed]
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Model type: [More Information Needed]
- Language(s) (NLP): [More Information Needed]
- License: [More Information Needed]
- Finetuned from model [optional]: [More Information Needed]
Model Sources [optional]
- Repository: [More Information Needed]
- Paper [optional]: [More Information Needed]
- Demo [optional]: [More Information Needed]
Uses
Direct Use
[More Information Needed]
Downstream Use [optional]
[More Information Needed]
Out-of-Scope Use
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
Training Details
Training Data
[More Information Needed]
Training Procedure
Preprocessing [optional]
[More Information Needed]
Training Hyperparameters
- Training regime: [More Information Needed]
Speeds, Sizes, Times [optional]
[More Information Needed]
Evaluation
Testing Data, Factors & Metrics
Testing Data
[More Information Needed]
Factors
[More Information Needed]
Metrics
[More Information Needed]
Results
[More Information Needed]
Summary
Model Examination [optional]
[More Information Needed]
Environmental Impact
Carbon emissions can be estimated using the Machine Learning Impact calculator presented in Lacoste et al. (2019).
- Hardware Type: [More Information Needed]
- Hours used: [More Information Needed]
- Cloud Provider: [More Information Needed]
- Compute Region: [More Information Needed]
- Carbon Emitted: [More Information Needed]
Technical Specifications [optional]
Model Architecture and Objective
[More Information Needed]
Compute Infrastructure
[More Information Needed]
Hardware
[More Information Needed]
Software
[More Information Needed]
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Model Card Authors [optional]
[More Information Needed]
Model Card Contact
[More Information Needed]
Sample Use
以下は、elyza-tasks-100-TV_0.jsonlの回答のためのコードです。
# Google Colab の場合は上記の環境構築手順を行なわず、単にこのセルから実行していってください。
!pip uninstall unsloth -y
!pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
# Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
!pip install --upgrade torch
!pip install --upgrade xformers
# notebookでインタラクティブな表示を可能とする(ただし、うまく動かない場合あり)
# Google Colabでは実行不要
!pip install ipywidgets --upgrade
# Install Flash Attention 2 for softcapping support
import torch
if torch.cuda.get_device_capability()[0] >= 8:
!pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
# Hugging Face Token を指定
# 下記の URL から Hugging Face Token を取得できますので下記の HF_TOKEN に入れてください。
# Write権限を付与してください。
# https://huggingface.co/settings/tokens
HF_TOKEN = "your-token" #@param {type:"string"}
# あるいは Google Colab シークレットを使う場合、左のサイドバーより🔑マークをクリック
# HF_TOKEN という名前で Value に Hugging Face Token を入れてください。
# ノートブックからのアクセスのトグルをオンにし、下記の二行のコードのコメントアウトを外してください。
# from google.colab import userdata
# HF_TOKEN=userdata.get('HF_TOKEN')
# llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
from unsloth import FastLanguageModel
import torch
max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
dtype = None # Noneにしておけば自動で設定
load_in_4bit = True # 今回は13Bモデルを扱うためTrue
model_id = "llm-jp/llm-jp-3-13b"
new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
# FastLanguageModel インスタンスを作成
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=model_id,
dtype=dtype,
load_in_4bit=load_in_4bit,
trust_remote_code=True,
)
# SFT用のモデルを用意
model = FastLanguageModel.get_peft_model(
model,
r = 32,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 32,
lora_dropout = 0.05,
bias = "none",
use_gradient_checkpointing = "unsloth",
random_state = 3407,
use_rslora = False,
loftq_config = None,
max_seq_length = max_seq_length,
)
from datasets import load_dataset
dataset = load_dataset("json", data_files="/content/news_summaries.jsonl")
# パスの指定にご注意ください。アップロードしたファイルを右クリックし、「パスをコピー」をクリック、上記の data_files と合致していることをご確認ください。Omnicampus のディレクトリ構造とは異なるかもしれません。
# データセットのカラム名を確認
print("Dataset columns:", dataset.column_names)
# 安全なフォーマット関数を定義
def formatting_prompts_func(examples):
try:
# 動的にキーを判定
key = "text" if "text" in examples else next(iter(examples.keys()))
input_text = examples[key]
# カスタム処理
return {"formatted_text": f"Processed: {input_text}"}
except KeyError:
print(f"Key error for examples: {examples}")
return {}
# フィルタリング(必要に応じて)
if "text" not in dataset.column_names:
print("Warning: 'text' column not found. Filtering dataset...")
dataset = dataset.filter(lambda example: "text" in example)
# map を適用
dataset = dataset.map(
formatting_prompts_func,
num_proc=4 # 並列処理
)
# 処理結果を確認
print(dataset)
# データセットのカラムを確認
print(dataset.column_names) # 現在のカラム名を表示
# `formatting_prompts_func`の修正
def formatting_prompts_func(examples):
# ここでは 'summary' カラムを使用
input_data = examples["summary"] # 入力データを 'summary' から取得
# ここでinput_dataを使った処理を続ける
return {"formatted_summary": input_data} # フォーマットした結果を返す
# 各データにフォーマットを適用
dataset = dataset.map(
formatting_prompts_func,
num_proc=4, # 並列処理数を指定
)
# 結果を確認
print(dataset)
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM
from trl import SFTTrainer
import logging
# ロギングの設定 - デバッグに非常に有効
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def prepare_dataset(dataset_name, split='train'):
try:
# データセットの読み込み
dataset = load_dataset(dataset_name, split=split)
# データセットの存在と内容の確認
if len(dataset) == 0:
logger.error(f"データセット {dataset_name} が空です。")
raise ValueError("データセットにデータがありません。")
logger.info(f"データセットのサイズ: {len(dataset)}")
logger.info(f"データセットの最初のサンプル: {dataset[0]}")
return dataset
except Exception as e:
logger.error(f"データセット読み込み中にエラーが発生: {e}")
raise
def prepare_model_and_tokenizer(model_name):
try:
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
return model, tokenizer
except Exception as e:
logger.error(f"モデルとトークナイザーの読み込み中にエラーが発生: {e}")
raise
def main():
try:
# データセットとモデルの設定
dataset_name = "your_dataset_name" # 実際のデータセット名に置き換えてください
model_name = "your_base_model" # 使用するモデル名に置き換えてください
# データセットの準備
train_dataset = prepare_dataset(dataset_name)
# モデルとトークナイザーの準備
model, tokenizer = prepare_model_and_tokenizer(model_name)
# トレーナーの設定
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=train_dataset,
dataset_text_field="text", # データセットの適切なテキストフィールドに置き換えてください
max_seq_length=512
)
# トレーニングの開始
trainer.train()
except Exception as e:
logger.error(f"トレーニング中に致命的なエラーが発生: {e}")
if __name__ == "__main__":
main()
#@title 現在のメモリ使用量を表示
gpu_stats = torch.cuda.get_device_properties(0)
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
print(f"{start_gpu_memory} GB of memory reserved.")
from transformers import AutoTokenizer, GPT2LMHeadModel
# ドキュメントをトークナイザーで準備
tokenizer = AutoTokenizer.from_pretrained("gpt2") # 適切なモデル名を使用
tokenizer.add_special_tokens({'pad_token': '[PAD]'}) # パディングトークンを設定
model = GPT2LMHeadModel.from_pretrained("gpt2") # 同じモデルをロード
model.resize_token_embeddings(len(tokenizer)) # トークン数をモデルに反映
def preprocess_data(examples):
return tokenizer(examples["text"], truncation=True, padding="max_length", max_length=128)
# データセットをトークナイズ
tokenized_dataset = dataset.map(preprocess_data, batched=True)
# ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
# データセットの読み込み。
# omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
import json
datasets = []
with open("/content//elyza-tasks-100-TV_0.jsonl", "r") as f:
item = ""
for line in f:
line = line.strip()
item += line
if item.endswith("}"):
datasets.append(json.loads(item))
item = ""
from transformers import AutoModelForCausalLM, AutoTokenizer
# モデルとトークナイザーの準備
tokenizer = AutoTokenizer.from_pretrained("gpt2") # 適切なモデル名を使用
model = AutoModelForCausalLM.from_pretrained("gpt2")
# 入力データの準備
inputs = tokenizer("ここに入力文を入れます", return_tensors="pt")
# generateメソッドの呼び出し(無効な引数を削除)
outputs = model.generate(
**inputs,
max_new_tokens=512, # 新しく生成するトークンの最大数
use_cache=True, # キャッシュを使用するか
do_sample=False, # サンプリングを行うかどうか
repetition_penalty=1.2 # 繰り返しペナルティ
)
# 出力のデコード
prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
print(prediction)
# jsonlで保存
with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
for result in results:
json.dump(result, f, ensure_ascii=False)
f.write('\n')
from transformers import AutoModelForCausalLM, AutoTokenizer
from huggingface_hub import login, HfApi
# Hugging Face Hubにアクセスするための認証トークンを設定
token = "your-token" # あなたのトークンをここに入力
login(token=token)
# モデルとトークナイザーの準備
model_name = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# LoRAアダプタの設定(必要に応じて)
# ここにLoRAの設定を追加
# プライベートリポジトリにモデルを保存
new_model_id = "LoRA_template_unsloth_1" # 保存するモデル名を指定
api = HfApi()
# リポジトリをプライベートとして作成
api.create_repo(new_model_id + "_lora", private=True)
# モデルとトークナイザーをHugging Face Hubにアップロード
model.push_to_hub(new_model_id + "_lora", private=True)
tokenizer.push_to_hub(new_model_id + "_lora", private=True)
print(f"Model and tokenizer uploaded to the private repository: {new_model_id + '_lora'}")
- Downloads last month
- 11