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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
absl-py==2.1.0
|
| 2 |
+
accelerate==1.1.1
|
| 3 |
+
aiohappyeyeballs==2.4.3
|
| 4 |
+
aiohttp==3.10.10
|
| 5 |
+
aiosignal==1.3.1
|
| 6 |
+
airportsdata==20241001
|
| 7 |
+
annotated-types==0.7.0
|
| 8 |
+
anyio==4.8.0
|
| 9 |
+
asttokens==2.4.1
|
| 10 |
+
async-timeout==4.0.3
|
| 11 |
+
attrs==24.2.0
|
| 12 |
+
bitsandbytes==0.44.1
|
| 13 |
+
boto3==1.35.58
|
| 14 |
+
botocore==1.35.58
|
| 15 |
+
certifi==2024.8.30
|
| 16 |
+
charset-normalizer==3.4.0
|
| 17 |
+
click==8.1.7
|
| 18 |
+
cloudpickle==3.1.0
|
| 19 |
+
colorama==0.4.6
|
| 20 |
+
comm==0.2.2
|
| 21 |
+
contourpy==1.3.1
|
| 22 |
+
cuda-python==12.6.2
|
| 23 |
+
cudf-polars-cu12==24.10.1
|
| 24 |
+
cycler==0.12.1
|
| 25 |
+
datasets==3.1.0
|
| 26 |
+
debugpy==1.8.8
|
| 27 |
+
decorator==5.1.1
|
| 28 |
+
dill==0.3.8
|
| 29 |
+
diskcache==5.6.3
|
| 30 |
+
docker==7.1.0
|
| 31 |
+
docker-pycreds==0.4.0
|
| 32 |
+
docstring_parser==0.16
|
| 33 |
+
exceptiongroup==1.2.2
|
| 34 |
+
executing==2.1.0
|
| 35 |
+
fastapi==0.115.8
|
| 36 |
+
fastjsonschema==2.20.0
|
| 37 |
+
filelock==3.16.1
|
| 38 |
+
fonttools==4.54.1
|
| 39 |
+
frozenlist==1.5.0
|
| 40 |
+
fsspec==2024.9.0
|
| 41 |
+
gitdb==4.0.11
|
| 42 |
+
GitPython==3.1.43
|
| 43 |
+
graphviz==0.20.3
|
| 44 |
+
grpcio==1.68.1
|
| 45 |
+
h11==0.14.0
|
| 46 |
+
hf_transfer==0.1.8
|
| 47 |
+
httptools==0.6.4
|
| 48 |
+
huggingface-hub==0.27.1
|
| 49 |
+
idna==3.10
|
| 50 |
+
iniconfig==2.0.0
|
| 51 |
+
interegular==0.3.3
|
| 52 |
+
ipykernel==6.29.5
|
| 53 |
+
ipython==8.29.0
|
| 54 |
+
ipywidgets==8.1.5
|
| 55 |
+
jedi==0.19.2
|
| 56 |
+
Jinja2==3.1.4
|
| 57 |
+
jmespath==1.0.1
|
| 58 |
+
joblib==1.4.2
|
| 59 |
+
jsonschema==4.23.0
|
| 60 |
+
jsonschema-specifications==2024.10.1
|
| 61 |
+
jupyter_client==8.6.3
|
| 62 |
+
jupyter_core==5.7.2
|
| 63 |
+
jupyterlab_widgets==3.0.13
|
| 64 |
+
kiwisolver==1.4.7
|
| 65 |
+
lark==1.2.2
|
| 66 |
+
libcudf-cu12==24.10.1
|
| 67 |
+
litserve==0.2.6
|
| 68 |
+
llvmlite==0.43.0
|
| 69 |
+
lxml==5.3.0
|
| 70 |
+
Markdown==3.7
|
| 71 |
+
markdown-it-py==3.0.0
|
| 72 |
+
MarkupSafe==3.0.2
|
| 73 |
+
matplotlib==3.9.2
|
| 74 |
+
matplotlib-inline==0.1.7
|
| 75 |
+
mdurl==0.1.2
|
| 76 |
+
metaflow==2.10.0
|
| 77 |
+
metaflow-card-html==1.0.2
|
| 78 |
+
mpmath==1.3.0
|
| 79 |
+
multidict==6.1.0
|
| 80 |
+
multiprocess==0.70.16
|
| 81 |
+
nbformat==5.10.4
|
| 82 |
+
nest-asyncio==1.6.0
|
| 83 |
+
networkx==3.2.1
|
| 84 |
+
numba==0.60.0
|
| 85 |
+
numpy==1.26.4
|
| 86 |
+
nvidia-cublas-cu11==11.11.3.6
|
| 87 |
+
nvidia-cublas-cu12==12.4.5.8
|
| 88 |
+
nvidia-cuda-cupti-cu11==11.8.87
|
| 89 |
+
nvidia-cuda-cupti-cu12==12.4.127
|
| 90 |
+
nvidia-cuda-nvrtc-cu11==11.8.89
|
| 91 |
+
nvidia-cuda-nvrtc-cu12==12.4.127
|
| 92 |
+
nvidia-cuda-runtime-cu11==11.8.89
|
| 93 |
+
nvidia-cuda-runtime-cu12==12.4.127
|
| 94 |
+
nvidia-cudnn-cu11==9.1.0.70
|
| 95 |
+
nvidia-cudnn-cu12==9.1.0.70
|
| 96 |
+
nvidia-cufft-cu11==10.9.0.58
|
| 97 |
+
nvidia-cufft-cu12==11.2.1.3
|
| 98 |
+
nvidia-curand-cu11==10.3.0.86
|
| 99 |
+
nvidia-curand-cu12==10.3.5.147
|
| 100 |
+
nvidia-cusolver-cu11==11.4.1.48
|
| 101 |
+
nvidia-cusolver-cu12==11.6.1.9
|
| 102 |
+
nvidia-cusparse-cu11==11.7.5.86
|
| 103 |
+
nvidia-cusparse-cu12==12.3.1.170
|
| 104 |
+
nvidia-nccl-cu11==2.21.5
|
| 105 |
+
nvidia-nccl-cu12==2.21.5
|
| 106 |
+
nvidia-nvjitlink-cu12==12.4.127
|
| 107 |
+
nvidia-nvtx-cu11==11.8.86
|
| 108 |
+
nvidia-nvtx-cu12==12.4.127
|
| 109 |
+
nvtx==0.2.10
|
| 110 |
+
outlines==0.1.3
|
| 111 |
+
outlines_core==0.1.14
|
| 112 |
+
packaging==24.2
|
| 113 |
+
pandas==2.2.3
|
| 114 |
+
parso==0.8.4
|
| 115 |
+
peft==0.13.2
|
| 116 |
+
pexpect==4.9.0
|
| 117 |
+
pillow==11.0.0
|
| 118 |
+
platformdirs==4.3.6
|
| 119 |
+
plotly==5.24.0
|
| 120 |
+
pluggy==1.5.0
|
| 121 |
+
polars==1.8.2
|
| 122 |
+
prompt_toolkit==3.0.48
|
| 123 |
+
propcache==0.2.0
|
| 124 |
+
protobuf==3.20.3
|
| 125 |
+
psutil==6.1.0
|
| 126 |
+
ptyprocess==0.7.0
|
| 127 |
+
pure_eval==0.2.3
|
| 128 |
+
pyarrow==17.0.0
|
| 129 |
+
pycountry==24.6.1
|
| 130 |
+
pydantic==2.9.2
|
| 131 |
+
pydantic_core==2.23.4
|
| 132 |
+
pydot==1.4.2
|
| 133 |
+
Pygments==2.18.0
|
| 134 |
+
pylibcudf-cu12==24.10.1
|
| 135 |
+
pyparsing==3.2.0
|
| 136 |
+
pytest==8.3.3
|
| 137 |
+
python-dateutil==2.9.0.post0
|
| 138 |
+
python-dotenv==1.0.1
|
| 139 |
+
python-multipart==0.0.20
|
| 140 |
+
pytz==2024.2
|
| 141 |
+
PyYAML==6.0.2
|
| 142 |
+
pyzmq==26.2.0
|
| 143 |
+
referencing==0.35.1
|
| 144 |
+
regex==2024.11.6
|
| 145 |
+
requests==2.32.3
|
| 146 |
+
-e git+https://github.com/aurelienmorgan/retrain-pipelines.git@9bbdca8a19b421b90a2640a250d8549680898f9b#egg=retrain_pipelines&subdirectory=pkg_src
|
| 147 |
+
rich==13.9.4
|
| 148 |
+
rmm-cu12==24.10.0
|
| 149 |
+
rpds-py==0.21.0
|
| 150 |
+
s3transfer==0.10.3
|
| 151 |
+
safetensors==0.4.5
|
| 152 |
+
scikit-learn==1.5.1
|
| 153 |
+
scipy==1.14.1
|
| 154 |
+
sentencepiece==0.2.0
|
| 155 |
+
sentry-sdk==2.19.0
|
| 156 |
+
setproctitle==1.3.4
|
| 157 |
+
shtab==1.7.1
|
| 158 |
+
six==1.16.0
|
| 159 |
+
smmap==5.0.1
|
| 160 |
+
sniffio==1.3.1
|
| 161 |
+
stack-data==0.6.3
|
| 162 |
+
starlette==0.45.3
|
| 163 |
+
sympy==1.13.1
|
| 164 |
+
tenacity==9.0.0
|
| 165 |
+
tensorboard==2.18.0
|
| 166 |
+
tensorboard-data-server==0.7.2
|
| 167 |
+
threadpoolctl==3.5.0
|
| 168 |
+
tokenizers==0.20.3
|
| 169 |
+
tomli==2.1.0
|
| 170 |
+
torch==2.5.0
|
| 171 |
+
tornado==6.4.1
|
| 172 |
+
tqdm==4.67.0
|
| 173 |
+
traitlets==5.14.3
|
| 174 |
+
transformers==4.46.2
|
| 175 |
+
triton==3.1.0
|
| 176 |
+
trl==0.12.0
|
| 177 |
+
typing_extensions==4.12.2
|
| 178 |
+
tyro==0.8.14
|
| 179 |
+
tzdata==2024.2
|
| 180 |
+
unsloth==2024.11.5
|
| 181 |
+
unsloth_zoo==2024.11.4
|
| 182 |
+
urllib3==2.2.3
|
| 183 |
+
uvicorn==0.34.0
|
| 184 |
+
uvloop==0.21.0
|
| 185 |
+
wandb==0.18.7
|
| 186 |
+
watchfiles==1.0.4
|
| 187 |
+
wcwidth==0.2.13
|
| 188 |
+
websockets==15.0
|
| 189 |
+
Werkzeug==3.1.3
|
| 190 |
+
widgetsnbextension==4.0.13
|
| 191 |
+
xformers==0.0.28.post2
|
| 192 |
+
xxhash==3.5.0
|
| 193 |
+
yarl==1.17.1
|
v0.7_20250318_190040840_UTC/retraining_pipeline.py
ADDED
|
@@ -0,0 +1,2159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from unsloth import FastLanguageModel, \
|
| 3 |
+
is_bfloat16_supported, UnslothTrainer, \
|
| 4 |
+
UnslothTrainingArguments
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
import gc
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
import shutil
|
| 15 |
+
import logging
|
| 16 |
+
import traceback
|
| 17 |
+
import subprocess
|
| 18 |
+
import importlib.util
|
| 19 |
+
from enum import Enum
|
| 20 |
+
from io import StringIO
|
| 21 |
+
from textwrap import dedent
|
| 22 |
+
from datetime import datetime
|
| 23 |
+
from contextlib import redirect_stdout
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import pandas as pd
|
| 27 |
+
|
| 28 |
+
import polars as pl
|
| 29 |
+
from polars.exceptions import ComputeError
|
| 30 |
+
|
| 31 |
+
import matplotlib
|
| 32 |
+
import matplotlib.pyplot as plt
|
| 33 |
+
|
| 34 |
+
from jinja2 import Environment, FileSystemLoader
|
| 35 |
+
|
| 36 |
+
from metaflow import FlowSpec, step, Parameter, JSONType, \
|
| 37 |
+
IncludeFile, current, metaflow_config as mf_config, \
|
| 38 |
+
resources, Flow, Task, card
|
| 39 |
+
from metaflow.current import Current
|
| 40 |
+
from metaflow.cards import Image, Table, Markdown, \
|
| 41 |
+
Artifact, get_cards
|
| 42 |
+
|
| 43 |
+
from datasets import load_dataset, Dataset, DatasetDict
|
| 44 |
+
from datasets.config import HF_DATASETS_CACHE, HF_CACHE_HOME
|
| 45 |
+
from huggingface_hub import list_repo_commits
|
| 46 |
+
from transformers import AutoTokenizer
|
| 47 |
+
from transformers.utils import logging as hf_logging
|
| 48 |
+
|
| 49 |
+
from retrain_pipelines import __version__
|
| 50 |
+
from retrain_pipelines.dataset.hf_utils import get_lazy_df, \
|
| 51 |
+
get_column_info, iterable_dataset_multi_buffer_sampler, \
|
| 52 |
+
push_dataset_version_to_hub
|
| 53 |
+
from retrain_pipelines.dataset.tool_calls import \
|
| 54 |
+
get_unique_tools, count_tool_occurrences, \
|
| 55 |
+
plot_tools_occurences, column_words_stats, \
|
| 56 |
+
plot_words_count
|
| 57 |
+
from retrain_pipelines.utils.hf_utils import \
|
| 58 |
+
get_new_repo_minor_version, push_files_to_hub_repo_branch
|
| 59 |
+
from retrain_pipelines.utils import create_requirements
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class LocalServeReadinessEnum(Enum):
|
| 63 |
+
"""
|
| 64 |
+
tracking local-serve (infra-validation)
|
| 65 |
+
status using a "3+"-states enum :
|
| 66 |
+
- "-1" for "not applicable"
|
| 67 |
+
(i.e. "model version not blessed"),
|
| 68 |
+
- "0/1" bool for failure/success.
|
| 69 |
+
"""
|
| 70 |
+
NOT_APPLICABLE = -1
|
| 71 |
+
FAILURE = 0
|
| 72 |
+
FAILURE_NO_DOCKER = 2
|
| 73 |
+
SUCCESS = 1
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class UnslothFuncCallFlow(FlowSpec):
|
| 77 |
+
"""
|
| 78 |
+
Training pipeline
|
| 79 |
+
"""
|
| 80 |
+
# @see https://github.com/unslothai/unsloth/wiki
|
| 81 |
+
|
| 82 |
+
#--- flow parameters -------------------------------------------------------
|
| 83 |
+
|
| 84 |
+
RETRAIN_PIPELINE_TYPE = "mf_unsloth_func_call_litserve"
|
| 85 |
+
# in order to share the config across subprocesses
|
| 86 |
+
os.environ["retrain_pipeline_type"] = RETRAIN_PIPELINE_TYPE
|
| 87 |
+
|
| 88 |
+
hf_dataset = Parameter(
|
| 89 |
+
"hf_dataset",
|
| 90 |
+
help="dict with 'repo_id' and 'commit_hash' keys. " + \
|
| 91 |
+
"if 'commit_hash is None, falls back to latest version " +\
|
| 92 |
+
"of the dataset available in parquet format.\n" +
|
| 93 |
+
"Note that there are 3 required 'attributes' of type " + \
|
| 94 |
+
"str, list[str], list[str]",
|
| 95 |
+
type=JSONType,
|
| 96 |
+
default=dedent("""{
|
| 97 |
+
"repo_id": "Salesforce/xlam-function-calling-60k",
|
| 98 |
+
"config_name": "",
|
| 99 |
+
"commit_hash": "",
|
| 100 |
+
"attributes": {
|
| 101 |
+
"query_attr": "query",
|
| 102 |
+
"answers_attr": "answers",
|
| 103 |
+
"tools_attr": "tools"
|
| 104 |
+
}
|
| 105 |
+
}""").replace("'", '"').strip('"')
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
augmentation_rate = Parameter(
|
| 109 |
+
"augmentation_rate",
|
| 110 |
+
type=float,
|
| 111 |
+
default=.05,
|
| 112 |
+
help="proportion of records to be augmented "+\
|
| 113 |
+
"(x% of original dataset is created"+\
|
| 114 |
+
" as additional augmented datapoints), i.e. "+\
|
| 115 |
+
"truncated queries to serve as negative examples, "+\
|
| 116 |
+
"meaning they trigger no tool call "+\
|
| 117 |
+
"due to info incompleteness."
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
hf_enrich_dataset = Parameter(
|
| 121 |
+
"hf_enrich_dataset",
|
| 122 |
+
help="dict with 'repo_id', 'config_name' and 'commit_hash', "+\
|
| 123 |
+
"query_attribute' and 'query_attribute_handler' keys. "+\
|
| 124 |
+
"if 'commit_hash is None, falls back to latest version "+\
|
| 125 |
+
"of the dataset available in parquet format."+\
|
| 126 |
+
"'query_attribute' depicts the dataset attribute "+\
|
| 127 |
+
"from which 'queries' are to be sampled."+\
|
| 128 |
+
"'query_attribute_handler' serves for attributes "+\
|
| 129 |
+
"that have complex structure, "+\
|
| 130 |
+
"other than 'string' datatype.",
|
| 131 |
+
type=JSONType,
|
| 132 |
+
# @see https://huggingface.co/datasets/google-research-datasets/natural_questions
|
| 133 |
+
default=dedent("""{
|
| 134 |
+
"repo_id": "lighteval/natural_questions_clean",
|
| 135 |
+
"config_name": "",
|
| 136 |
+
"commit_hash": "",
|
| 137 |
+
"query_attribute": "question",
|
| 138 |
+
"query_attribute_handler": "lambda x: x"
|
| 139 |
+
}""").replace("'", '"').strip('"')
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
enrichment_rate = Parameter(
|
| 143 |
+
"enrichment_rate",
|
| 144 |
+
type=float,
|
| 145 |
+
default=.1,
|
| 146 |
+
help="proportion of records "+\
|
| 147 |
+
"to be added from the 'hf_enrich_dataset'"+\
|
| 148 |
+
"(x% of original dataset is sampled and"+\
|
| 149 |
+
" added as enriching datapoints), i.e. "+\
|
| 150 |
+
"queries to serve as negative examples, "+\
|
| 151 |
+
"due to their complete disconnexion "+\
|
| 152 |
+
"to tool calling situations."
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
dataset_repo_id = Parameter(
|
| 156 |
+
"dataset_repo_id",
|
| 157 |
+
type=str,
|
| 158 |
+
default="retrain-pipelines/func_calls",
|
| 159 |
+
help="The 'repo_id' to be used " + \
|
| 160 |
+
"for the Hugging Face dataset version push " + \
|
| 161 |
+
"(will be created at runtime" + \
|
| 162 |
+
" if doesn't already exist)."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
hf_base_model = Parameter(
|
| 166 |
+
"hf_base_model",
|
| 167 |
+
help="dict with 'repo_id' and 'commit_hash' keys."+\
|
| 168 |
+
"if 'commit_hash is None, falls back "+\
|
| 169 |
+
"to latest available version of the model.",
|
| 170 |
+
type=JSONType,
|
| 171 |
+
default=dedent("""{
|
| 172 |
+
"repo_id": "unsloth/Qwen2.5-1.5B",
|
| 173 |
+
"commit_hash": ""
|
| 174 |
+
}""").replace("'", '"').strip('"')
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
cpt_training_args = Parameter(
|
| 178 |
+
"cpt_training_args",
|
| 179 |
+
help="dict with `TrainingArguments` params "+\
|
| 180 |
+
"for the CPT job.",
|
| 181 |
+
type=JSONType,
|
| 182 |
+
default=dedent("""{
|
| 183 |
+
"warmup_ratio": 0.1,
|
| 184 |
+
"num_train_epochs": 1
|
| 185 |
+
}""").replace("'", '"').strip('"')
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
sft_training_args = Parameter(
|
| 189 |
+
"sft_training_args",
|
| 190 |
+
help="dict with `TrainingArguments` params "+\
|
| 191 |
+
"for the SFT job.",
|
| 192 |
+
type=JSONType,
|
| 193 |
+
default=dedent("""{
|
| 194 |
+
"warmup_ratio": 0.1,
|
| 195 |
+
"num_train_epochs": 1
|
| 196 |
+
}""").replace("'", '"').strip('"')
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
model_repo_id = Parameter(
|
| 200 |
+
"model_repo_id",
|
| 201 |
+
type=str,
|
| 202 |
+
default="retrain-pipelines/function_caller",
|
| 203 |
+
help="The 'repo_id' to be used " + \
|
| 204 |
+
"for the Hugging Face model version push " + \
|
| 205 |
+
"(will be created at runtime" + \
|
| 206 |
+
" if doesn't already exist)."
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
default_pipeline_card_module_dir = \
|
| 210 |
+
os.path.dirname(
|
| 211 |
+
importlib.util.find_spec(
|
| 212 |
+
f"retrain_pipelines.pipeline_card."+
|
| 213 |
+
f"{RETRAIN_PIPELINE_TYPE}"
|
| 214 |
+
).origin)
|
| 215 |
+
pipeline_card_artifacts_path = Parameter(
|
| 216 |
+
"pipeline_card_artifacts_path",
|
| 217 |
+
type=str,
|
| 218 |
+
default=default_pipeline_card_module_dir,
|
| 219 |
+
help="pipeline_card artifacts location "+\
|
| 220 |
+
"(i.e. dir hosting your optional " + \
|
| 221 |
+
" custom documentation files :" + \
|
| 222 |
+
" 'pipeline_card.py' and/or 'template.html'"+\
|
| 223 |
+
" and/or 'model_readme.py'"+\
|
| 224 |
+
" and/or 'model_readme_template.md'," +\
|
| 225 |
+
" and/or 'dataset_readme.py'"+\
|
| 226 |
+
" and/or 'dataset_readme_template.md' file), " +\
|
| 227 |
+
"if different from default."
|
| 228 |
+
)
|
| 229 |
+
@staticmethod
|
| 230 |
+
def copy_default_dataset_readme_module(
|
| 231 |
+
target_dir: str,
|
| 232 |
+
exists_ok: bool = False
|
| 233 |
+
) -> None:
|
| 234 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 235 |
+
if (
|
| 236 |
+
not exists_ok and
|
| 237 |
+
os.path.exists(os.path.join(target_dir, "dataset_readme.py"))
|
| 238 |
+
):
|
| 239 |
+
print("File already exists. Skipping copy.")
|
| 240 |
+
else:
|
| 241 |
+
filefullname = os.path.join(
|
| 242 |
+
UnslothFuncCallFlow.default_pipeline_card_module_dir,
|
| 243 |
+
"dataset_readme.py"
|
| 244 |
+
)
|
| 245 |
+
shutil.copy(filefullname, target_dir)
|
| 246 |
+
print(filefullname)
|
| 247 |
+
@staticmethod
|
| 248 |
+
def copy_default_dataset_readme_template(
|
| 249 |
+
target_dir: str,
|
| 250 |
+
exists_ok: bool = False
|
| 251 |
+
) -> None:
|
| 252 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 253 |
+
if (
|
| 254 |
+
not exists_ok and
|
| 255 |
+
os.path.exists(os.path.join(target_dir,
|
| 256 |
+
"dataset_readme_template.md"))
|
| 257 |
+
):
|
| 258 |
+
print("File already exists. Skipping copy.")
|
| 259 |
+
else:
|
| 260 |
+
filefullname = os.path.join(
|
| 261 |
+
UnslothFuncCallFlow.default_pipeline_card_module_dir,
|
| 262 |
+
"dataset_readme_template.md")
|
| 263 |
+
shutil.copy(filefullname, target_dir)
|
| 264 |
+
print(filefullname)
|
| 265 |
+
@staticmethod
|
| 266 |
+
def copy_default_model_readme_module(
|
| 267 |
+
target_dir: str,
|
| 268 |
+
exists_ok: bool = False
|
| 269 |
+
) -> None:
|
| 270 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 271 |
+
if (
|
| 272 |
+
not exists_ok and
|
| 273 |
+
os.path.exists(os.path.join(target_dir, "model_readme.py"))
|
| 274 |
+
):
|
| 275 |
+
print("File already exists. Skipping copy.")
|
| 276 |
+
else:
|
| 277 |
+
filefullname = os.path.join(
|
| 278 |
+
UnslothFuncCallFlow.default_pipeline_card_module_dir,
|
| 279 |
+
"model_readme.py"
|
| 280 |
+
)
|
| 281 |
+
shutil.copy(filefullname, target_dir)
|
| 282 |
+
print(filefullname)
|
| 283 |
+
@staticmethod
|
| 284 |
+
def copy_default_model_readme_template(
|
| 285 |
+
target_dir: str,
|
| 286 |
+
exists_ok: bool = False
|
| 287 |
+
) -> None:
|
| 288 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 289 |
+
if (
|
| 290 |
+
not exists_ok and
|
| 291 |
+
os.path.exists(os.path.join(target_dir,
|
| 292 |
+
"model_readme_template.md"))
|
| 293 |
+
):
|
| 294 |
+
print("File already exists. Skipping copy.")
|
| 295 |
+
else:
|
| 296 |
+
filefullname = os.path.join(
|
| 297 |
+
UnslothFuncCallFlow.default_pipeline_card_module_dir,
|
| 298 |
+
"model_readme_template.md")
|
| 299 |
+
shutil.copy(filefullname, target_dir)
|
| 300 |
+
print(filefullname)
|
| 301 |
+
@staticmethod
|
| 302 |
+
def copy_default_pipeline_card_module(
|
| 303 |
+
target_dir: str,
|
| 304 |
+
exists_ok: bool = False
|
| 305 |
+
) -> None:
|
| 306 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 307 |
+
if (
|
| 308 |
+
not exists_ok and
|
| 309 |
+
os.path.exists(os.path.join(target_dir, "pipeline_card.py"))
|
| 310 |
+
):
|
| 311 |
+
print("File already exists. Skipping copy.")
|
| 312 |
+
else:
|
| 313 |
+
filefullname = os.path.join(
|
| 314 |
+
UnslothFuncCallFlow.default_pipeline_card_module_dir,
|
| 315 |
+
"pipeline_card.py"
|
| 316 |
+
)
|
| 317 |
+
shutil.copy(filefullname, target_dir)
|
| 318 |
+
print(filefullname)
|
| 319 |
+
@staticmethod
|
| 320 |
+
def copy_default_pipeline_card_html_template(
|
| 321 |
+
target_dir: str,
|
| 322 |
+
exists_ok: bool = False
|
| 323 |
+
) -> None:
|
| 324 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 325 |
+
if (
|
| 326 |
+
not exists_ok and
|
| 327 |
+
os.path.exists(os.path.join(target_dir, "template.html"))
|
| 328 |
+
):
|
| 329 |
+
print("File already exists. Skipping copy.")
|
| 330 |
+
else:
|
| 331 |
+
filefullname = os.path.join(
|
| 332 |
+
UnslothFuncCallFlow.default_pipeline_card_module_dir,
|
| 333 |
+
"template.html")
|
| 334 |
+
shutil.copy(filefullname, target_dir)
|
| 335 |
+
print(filefullname)
|
| 336 |
+
|
| 337 |
+
del RETRAIN_PIPELINE_TYPE
|
| 338 |
+
|
| 339 |
+
#---------------------------------------------------------------------------
|
| 340 |
+
|
| 341 |
+
@step
|
| 342 |
+
def start(self):
|
| 343 |
+
print(f"{current.flow_name} - {current.run_id}")
|
| 344 |
+
|
| 345 |
+
# GPU availability
|
| 346 |
+
print(torch.cuda.get_device_name(0))
|
| 347 |
+
print(torch.__version__)
|
| 348 |
+
self.engine = "gpu" if torch.cuda.is_available() else "cpu"
|
| 349 |
+
|
| 350 |
+
# hf_dataset
|
| 351 |
+
hf_dataset_dict = \
|
| 352 |
+
get_lazy_df(
|
| 353 |
+
repo_id=self.hf_dataset["repo_id"],
|
| 354 |
+
commit_hash=self.hf_dataset["commit_hash"],
|
| 355 |
+
files_filter=(
|
| 356 |
+
self.hf_dataset['config_name']+"/.*\\.parquet"
|
| 357 |
+
if (
|
| 358 |
+
self.hf_dataset["config_name"] and
|
| 359 |
+
"" < self.hf_dataset["config_name"]
|
| 360 |
+
) else ".*\\.parquet"
|
| 361 |
+
),
|
| 362 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 363 |
+
)
|
| 364 |
+
try:
|
| 365 |
+
print(hf_dataset_dict["repo_id"], ", ",
|
| 366 |
+
hf_dataset_dict["commit_hash"], " - ",
|
| 367 |
+
hf_dataset_dict["commit_datetime"], "\n",
|
| 368 |
+
hf_dataset_dict["lazy_df"].explain())
|
| 369 |
+
except ComputeError as ex:
|
| 370 |
+
if "HF_TOKEN" not in os.environ:
|
| 371 |
+
print("Does the Hugging Face-hosted dataset " +
|
| 372 |
+
"require authentication ?",
|
| 373 |
+
file=sys.stderr, flush=True)
|
| 374 |
+
raise ex
|
| 375 |
+
self.hf_dataset_dict = hf_dataset_dict
|
| 376 |
+
|
| 377 |
+
# hf_enrich_dataset
|
| 378 |
+
print(self.hf_enrich_dataset)
|
| 379 |
+
hf_enrich_dataset_dict = \
|
| 380 |
+
get_lazy_df(
|
| 381 |
+
repo_id=self.hf_enrich_dataset["repo_id"],
|
| 382 |
+
commit_hash=self.hf_enrich_dataset["commit_hash"],
|
| 383 |
+
files_filter=(
|
| 384 |
+
self.hf_enrich_dataset['config_name']+"/.*\\.parquet"
|
| 385 |
+
if (
|
| 386 |
+
self.hf_enrich_dataset["config_name"] and
|
| 387 |
+
"" < self.hf_enrich_dataset["config_name"]
|
| 388 |
+
) else ".*\\.parquet"
|
| 389 |
+
),
|
| 390 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 391 |
+
)
|
| 392 |
+
print(' ; '.join(f"{k}: {hf_enrich_dataset_dict[k]}"
|
| 393 |
+
for k in ['commit_hash',
|
| 394 |
+
'commit_datetime']))
|
| 395 |
+
self.hf_enrich_dataset_dict = hf_enrich_dataset_dict
|
| 396 |
+
|
| 397 |
+
# hf_base_model
|
| 398 |
+
hf_base_model_commits = list_repo_commits(
|
| 399 |
+
repo_id=self.hf_base_model["repo_id"],
|
| 400 |
+
revision=(
|
| 401 |
+
None if (rev_commit_hash:=self.hf_base_model["commit_hash"]) == ""
|
| 402 |
+
else rev_commit_hash
|
| 403 |
+
),
|
| 404 |
+
repo_type="model",
|
| 405 |
+
token=os.getenv("HF_TOKEN", None))
|
| 406 |
+
self.hf_base_model_dict = {
|
| 407 |
+
"repo_id": self.hf_base_model["repo_id"],
|
| 408 |
+
"commit_hash": hf_base_model_commits[0].commit_id,
|
| 409 |
+
"commit_datetime": \
|
| 410 |
+
hf_base_model_commits[0].created_at
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
self.model_version_blessed = False
|
| 414 |
+
self.current_blessed_run = None
|
| 415 |
+
self.current_blessed_version_dict = None
|
| 416 |
+
current.run.remove_tag("model_version_blessed")
|
| 417 |
+
|
| 418 |
+
self.retrain_pipelines = f"retrain-pipelines {__version__}"
|
| 419 |
+
self.retrain_pipeline_type = os.environ["retrain_pipeline_type"]
|
| 420 |
+
|
| 421 |
+
self.serving_artifacts_local_folder = \
|
| 422 |
+
os.path.realpath(os.path.join(
|
| 423 |
+
os.path.dirname(__file__),
|
| 424 |
+
'..', '..', 'serving_artifacts',
|
| 425 |
+
os.path.sep.join(current.run.path_components)
|
| 426 |
+
))
|
| 427 |
+
|
| 428 |
+
if not os.path.exists(self.serving_artifacts_local_folder):
|
| 429 |
+
os.makedirs(self.serving_artifacts_local_folder)
|
| 430 |
+
|
| 431 |
+
self.unsloth_dir = os.path.join(
|
| 432 |
+
self.serving_artifacts_local_folder,
|
| 433 |
+
"Unsloth"
|
| 434 |
+
)
|
| 435 |
+
print(f"unsloth_dir : {self.unsloth_dir}")
|
| 436 |
+
self.cpt_model_dir = os.path.join(
|
| 437 |
+
self.unsloth_dir, "cpt_model")
|
| 438 |
+
self.sft_model_dir = os.path.join(
|
| 439 |
+
self.unsloth_dir, "sft_model")
|
| 440 |
+
|
| 441 |
+
self.next(self.eda)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@step
|
| 445 |
+
def eda(self):
|
| 446 |
+
"""
|
| 447 |
+
exploratory data analysis.
|
| 448 |
+
"""
|
| 449 |
+
|
| 450 |
+
############################
|
| 451 |
+
# features and label #
|
| 452 |
+
# basic counts #
|
| 453 |
+
############################
|
| 454 |
+
self.records_count = self.hf_dataset_dict["lazy_df"] \
|
| 455 |
+
.select(pl.len()).collect(engine=self.engine).item()
|
| 456 |
+
self.data_schema = get_column_info(
|
| 457 |
+
self.hf_dataset_dict["lazy_df"], engine=self.engine)
|
| 458 |
+
############################
|
| 459 |
+
|
| 460 |
+
############################
|
| 461 |
+
# Answers #
|
| 462 |
+
# tools count #
|
| 463 |
+
############################
|
| 464 |
+
struct_schema = pl.Struct([
|
| 465 |
+
pl.Field("name",
|
| 466 |
+
pl.String
|
| 467 |
+
),
|
| 468 |
+
pl.Field("arguments",
|
| 469 |
+
pl.List(pl.String) # we retrieve list of args names
|
| 470 |
+
# (without assigned values)
|
| 471 |
+
)
|
| 472 |
+
])
|
| 473 |
+
tool_answer_occurrences_df = \
|
| 474 |
+
count_tool_occurrences(
|
| 475 |
+
self.hf_dataset_dict["lazy_df"],
|
| 476 |
+
self.hf_dataset["attributes"]["answers_attr"],
|
| 477 |
+
struct_schema) \
|
| 478 |
+
.collect(engine=self.engine)
|
| 479 |
+
print(f"{tool_answer_occurrences_df['occurrences'].sum():,} " +
|
| 480 |
+
f"query/tool-calls pairs")
|
| 481 |
+
fig = plot_tools_occurences(tool_answer_occurrences_df,
|
| 482 |
+
title_prefix="Dataset answers - ")
|
| 483 |
+
self.answers_tools_count_fig = fig
|
| 484 |
+
############################
|
| 485 |
+
|
| 486 |
+
############################
|
| 487 |
+
# Query #
|
| 488 |
+
# words count #
|
| 489 |
+
############################
|
| 490 |
+
queries_max_length = self.hf_dataset_dict["lazy_df"].select(
|
| 491 |
+
pl.col(
|
| 492 |
+
self.hf_dataset["attributes"]["query_attr"]
|
| 493 |
+
).str.len_chars().max().alias("max_query_length")
|
| 494 |
+
).collect(engine=self.engine)
|
| 495 |
+
print(f"longuest query counts " +
|
| 496 |
+
f"{queries_max_length['max_query_length'][0]:,} characters")
|
| 497 |
+
|
| 498 |
+
# queries length quartiles
|
| 499 |
+
self.query_words_stats = \
|
| 500 |
+
column_words_stats(
|
| 501 |
+
self.hf_dataset_dict["lazy_df"],
|
| 502 |
+
self.hf_dataset["attributes"]["query_attr"]
|
| 503 |
+
).collect(engine=self.engine)
|
| 504 |
+
print(self.query_words_stats.to_pandas().to_string(index=False))
|
| 505 |
+
print("Two thirds of the records have a query with less than " +
|
| 506 |
+
f"{self.query_words_stats['q3'][0]} words.")
|
| 507 |
+
|
| 508 |
+
fig = plot_words_count(
|
| 509 |
+
self.hf_dataset_dict["lazy_df"],
|
| 510 |
+
column_name=self.hf_dataset["attributes"]["query_attr"],
|
| 511 |
+
engine=self.engine)
|
| 512 |
+
self.words_count_fig = fig
|
| 513 |
+
############################
|
| 514 |
+
|
| 515 |
+
############################
|
| 516 |
+
# hf_enrich_dataset #
|
| 517 |
+
# Query words count #
|
| 518 |
+
############################
|
| 519 |
+
enrich_question_words_stats = \
|
| 520 |
+
column_words_stats(
|
| 521 |
+
self.hf_enrich_dataset_dict['lazy_df'],
|
| 522 |
+
self.hf_enrich_dataset["query_attribute"],
|
| 523 |
+
column_attr_handler=eval(
|
| 524 |
+
self.hf_enrich_dataset["query_attribute_handler"])
|
| 525 |
+
).collect(engine=self.engine)
|
| 526 |
+
print(enrich_question_words_stats.to_pandas()
|
| 527 |
+
.to_string(index=False))
|
| 528 |
+
del enrich_question_words_stats
|
| 529 |
+
############################
|
| 530 |
+
|
| 531 |
+
self.next(self.augment_data)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@step
|
| 535 |
+
def augment_data(self):
|
| 536 |
+
"""
|
| 537 |
+
Add 'negative' examples, where
|
| 538 |
+
queries do not trigger any tool call.
|
| 539 |
+
To achieve that, we sample long user queries,
|
| 540 |
+
truncate at half words count, and
|
| 541 |
+
associate this to an empty list of tool-calls.
|
| 542 |
+
"""
|
| 543 |
+
"""
|
| 544 |
+
We only consider :
|
| 545 |
+
- records with longuest queries,
|
| 546 |
+
i.e. queries in the last quartile
|
| 547 |
+
of "queries with most word-counts"
|
| 548 |
+
(this is to avoid that 'truncated' queries
|
| 549 |
+
get really short)
|
| 550 |
+
- records with answers consisting
|
| 551 |
+
in a single tool-call
|
| 552 |
+
(in order to minimize the risk
|
| 553 |
+
that truncating actually gives
|
| 554 |
+
a valid answer with
|
| 555 |
+
one tool-call [or more])
|
| 556 |
+
|
| 557 |
+
Note on flow 'augmentation_rate' :
|
| 558 |
+
we add that many records (at most),
|
| 559 |
+
as quartiles size permits.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
print("Sampling within the population with more than " +
|
| 563 |
+
str(self.query_words_stats['q3'][0]) +
|
| 564 |
+
" words (longest queries quartile) =>")
|
| 565 |
+
|
| 566 |
+
samples_count = \
|
| 567 |
+
int(self.records_count * self.augmentation_rate)
|
| 568 |
+
print(f"would represent {samples_count:,.0f} " +
|
| 569 |
+
f"records to be sampled")
|
| 570 |
+
|
| 571 |
+
eligible_records_df = \
|
| 572 |
+
self.hf_dataset_dict["lazy_df"].filter(
|
| 573 |
+
pl.col(
|
| 574 |
+
self.hf_dataset["attributes"]["query_attr"]
|
| 575 |
+
)
|
| 576 |
+
.str.extract_all(r"\w+")
|
| 577 |
+
.map_elements(
|
| 578 |
+
lambda arr: len(arr),
|
| 579 |
+
return_dtype=pl.Int16)
|
| 580 |
+
.gt(self.query_words_stats['q3'][0])
|
| 581 |
+
& pl.col("answers")
|
| 582 |
+
.map_elements(
|
| 583 |
+
lambda x: len(json.loads(x)) == 1
|
| 584 |
+
if isinstance(x, str)
|
| 585 |
+
else False,
|
| 586 |
+
return_dtype=pl.Boolean)
|
| 587 |
+
) \
|
| 588 |
+
.collect(engine=self.engine)
|
| 589 |
+
eligible_records_count = \
|
| 590 |
+
eligible_records_df.select(pl.len())["len"][0]
|
| 591 |
+
print(f"eligible_records_count : " +
|
| 592 |
+
f"{eligible_records_count:,.0f}")
|
| 593 |
+
samples_count = min(samples_count, eligible_records_count)
|
| 594 |
+
self.actual_augmentation_rate = \
|
| 595 |
+
samples_count / self.records_count
|
| 596 |
+
print("actual augmentation rate : " +
|
| 597 |
+
f"{self.actual_augmentation_rate:.1%}")
|
| 598 |
+
sampled_records_df = eligible_records_df.sample(
|
| 599 |
+
n=samples_count
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
self.augmented_records_df = \
|
| 603 |
+
sampled_records_df.with_columns(
|
| 604 |
+
pl.col("query")
|
| 605 |
+
.map_elements(
|
| 606 |
+
lambda query:
|
| 607 |
+
" ".join(
|
| 608 |
+
query.split()[
|
| 609 |
+
:len(query.split()) // 2]),
|
| 610 |
+
return_dtype=pl.Utf8)
|
| 611 |
+
.alias("truncated_query")
|
| 612 |
+
).select([
|
| 613 |
+
pl.col("truncated_query").alias("query"),
|
| 614 |
+
pl.lit("[]").alias("answers")
|
| 615 |
+
])
|
| 616 |
+
print(self.augmented_records_df.height,
|
| 617 |
+
self.augmented_records_df.columns)
|
| 618 |
+
|
| 619 |
+
self.next(self.enrich_data)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
@step
|
| 623 |
+
def enrich_data(self):
|
| 624 |
+
"""
|
| 625 |
+
Further enrich our dataset with 'negative' records from
|
| 626 |
+
another dataset (can be general-purpose text dataset)
|
| 627 |
+
as specified by the the flow 'hf_enrich_dataset' argument.
|
| 628 |
+
"""
|
| 629 |
+
"""
|
| 630 |
+
Note : we here use the Hugging Face `datasets` library
|
| 631 |
+
in 'streaming' mode for records sampling.
|
| 632 |
+
"""
|
| 633 |
+
|
| 634 |
+
hf_enrich_ds = load_dataset(
|
| 635 |
+
path=self.hf_enrich_dataset["repo_id"],
|
| 636 |
+
name=self.hf_enrich_dataset["config_name"],
|
| 637 |
+
revision=self.hf_enrich_dataset_dict["commit_hash"],
|
| 638 |
+
streaming=True)
|
| 639 |
+
print(hf_enrich_ds["train"])
|
| 640 |
+
|
| 641 |
+
samples_count = \
|
| 642 |
+
int(self.records_count * self.enrichment_rate)
|
| 643 |
+
print(f"Samplig {samples_count:,.0f} records")
|
| 644 |
+
|
| 645 |
+
query_attribute_handler = \
|
| 646 |
+
eval(self.hf_enrich_dataset["query_attribute_handler"])
|
| 647 |
+
samples_iterator = iterable_dataset_multi_buffer_sampler(
|
| 648 |
+
hf_enrich_ds["train"],
|
| 649 |
+
total_samples=samples_count,
|
| 650 |
+
attributes_selector=\
|
| 651 |
+
(lambda x:query_attribute_handler(
|
| 652 |
+
x[self.hf_enrich_dataset["query_attribute"]])),
|
| 653 |
+
buffer_size=3_000,
|
| 654 |
+
num_passes=3,
|
| 655 |
+
seed=None
|
| 656 |
+
)
|
| 657 |
+
# Capitalize and add end punctuation if missing
|
| 658 |
+
start_time = time.time()
|
| 659 |
+
print("Starting sample enriching records, " +
|
| 660 |
+
"this may take some time if the source dataset " +
|
| 661 |
+
"has a complex structure..")
|
| 662 |
+
samples_list = [
|
| 663 |
+
s.capitalize() + ("" if s[-1] in ".!?" else "?")
|
| 664 |
+
for s in samples_iterator]
|
| 665 |
+
elapsed_time = time.time() - start_time
|
| 666 |
+
print(f".. sampling completed " +
|
| 667 |
+
f"({int(elapsed_time // 3_600)}h:" +
|
| 668 |
+
f"{int((elapsed_time % 3_600) // 60)}m:" +
|
| 669 |
+
f"{int(elapsed_time % 60)}s).")
|
| 670 |
+
enriched_records_df = pl.DataFrame(
|
| 671 |
+
{"query": samples_list,
|
| 672 |
+
"answers": \
|
| 673 |
+
["[]"] * \
|
| 674 |
+
len(samples_list)}
|
| 675 |
+
)
|
| 676 |
+
self.enriched_records_df = enriched_records_df
|
| 677 |
+
|
| 678 |
+
self.next(self.dataset_to_hub)
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
@step
|
| 682 |
+
def dataset_to_hub(self):
|
| 683 |
+
"""
|
| 684 |
+
Push to hub dataset version
|
| 685 |
+
- continued pre-training dataset
|
| 686 |
+
- training and validation splits of the
|
| 687 |
+
augmented and enriched
|
| 688 |
+
supervised finetuning dataset
|
| 689 |
+
- readme with versioning info
|
| 690 |
+
"""
|
| 691 |
+
|
| 692 |
+
#############################
|
| 693 |
+
# case of user-provided #
|
| 694 |
+
# documentation artifact(s) #
|
| 695 |
+
#############################
|
| 696 |
+
# note that user can provide either
|
| 697 |
+
# 'pipeline_card.py' or 'template.html'
|
| 698 |
+
# or 'dataset_readme.py'
|
| 699 |
+
# or 'dataset_readme_template.md'
|
| 700 |
+
# or 'model_readme.py'
|
| 701 |
+
# or 'model_readme_template.md'
|
| 702 |
+
# or any combination of those
|
| 703 |
+
# when specifying custom
|
| 704 |
+
# 'pipeline_card_artifacts_path'
|
| 705 |
+
if (
|
| 706 |
+
"dataset_readme_template.md" in
|
| 707 |
+
os.listdir(self.pipeline_card_artifacts_path)
|
| 708 |
+
):
|
| 709 |
+
template_dir = self.pipeline_card_artifacts_path
|
| 710 |
+
else:
|
| 711 |
+
template_dir = os.path.dirname(
|
| 712 |
+
importlib.util.find_spec(
|
| 713 |
+
f"retrain_pipelines.pipeline_card."+
|
| 714 |
+
f"{os.getenv('retrain_pipeline_type')}"
|
| 715 |
+
).origin)
|
| 716 |
+
print(f"template_dir : '{template_dir}'")
|
| 717 |
+
#############################
|
| 718 |
+
if "dataset_readme.py" in os.listdir(
|
| 719 |
+
self.pipeline_card_artifacts_path):
|
| 720 |
+
from retrain_pipelines.utils import \
|
| 721 |
+
get_get_dataset_readme_content
|
| 722 |
+
get_dataset_readme_content = \
|
| 723 |
+
get_get_dataset_readme_content(
|
| 724 |
+
self.pipeline_card_artifacts_path)
|
| 725 |
+
else:
|
| 726 |
+
from retrain_pipelines.pipeline_card import \
|
| 727 |
+
get_dataset_readme_content
|
| 728 |
+
#############################
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
#############################
|
| 732 |
+
# augmented & enriched #
|
| 733 |
+
# finetuning dataset #
|
| 734 |
+
#############################
|
| 735 |
+
merged_df = pl.concat([
|
| 736 |
+
# dataset
|
| 737 |
+
self.hf_dataset_dict["lazy_df"].select([
|
| 738 |
+
self.hf_dataset["attributes"]["query_attr"],
|
| 739 |
+
self.hf_dataset["attributes"]["answers_attr"]
|
| 740 |
+
]).collect(engine=self.engine),
|
| 741 |
+
# truncated queries augmentation
|
| 742 |
+
self.augmented_records_df,
|
| 743 |
+
# enriching dataset
|
| 744 |
+
self.enriched_records_df
|
| 745 |
+
]).sample(
|
| 746 |
+
# shuffling
|
| 747 |
+
fraction=1,
|
| 748 |
+
shuffle=True,
|
| 749 |
+
with_replacement=False
|
| 750 |
+
)
|
| 751 |
+
merged_df = merged_df.sample(fraction=1, shuffle=True)
|
| 752 |
+
merged_df.rechunk()
|
| 753 |
+
print(("merged_df", f"{merged_df.shape[0]:,.0F}",
|
| 754 |
+
merged_df.columns))
|
| 755 |
+
|
| 756 |
+
pandas_df = merged_df.to_pandas()
|
| 757 |
+
train_size = int(0.8 * len(pandas_df))
|
| 758 |
+
print(f"validation : {len(pandas_df) - train_size}")
|
| 759 |
+
sft_dataset = DatasetDict({
|
| 760 |
+
"train": Dataset.from_pandas(pandas_df[:train_size]),
|
| 761 |
+
"validation": Dataset.from_pandas(pandas_df[train_size:])
|
| 762 |
+
})
|
| 763 |
+
#############################
|
| 764 |
+
|
| 765 |
+
#############################
|
| 766 |
+
# continued pre-training #
|
| 767 |
+
# dataset #
|
| 768 |
+
#############################
|
| 769 |
+
struct_schema = pl.Struct([
|
| 770 |
+
pl.Field("name", pl.String),
|
| 771 |
+
pl.Field("description", pl.String),
|
| 772 |
+
pl.Field(
|
| 773 |
+
"parameters",
|
| 774 |
+
pl.String # Use String to allow
|
| 775 |
+
# for varying structures
|
| 776 |
+
# (different tools indeed having
|
| 777 |
+
# different sets of parameters
|
| 778 |
+
# i.e. different parameters counts,
|
| 779 |
+
# datatypes and names)
|
| 780 |
+
# so parsing must be tolerant.
|
| 781 |
+
)
|
| 782 |
+
])
|
| 783 |
+
unique_tools_df = get_unique_tools(
|
| 784 |
+
self.hf_dataset_dict["lazy_df"],
|
| 785 |
+
tools_attr_name=\
|
| 786 |
+
self.hf_dataset["attributes"]["tools_attr"],
|
| 787 |
+
struct_schema=struct_schema
|
| 788 |
+
).collect(engine=self.engine)
|
| 789 |
+
unique_tools_arrow_table = unique_tools_df.to_arrow()
|
| 790 |
+
self.unique_tools_dataset = \
|
| 791 |
+
Dataset(unique_tools_arrow_table)
|
| 792 |
+
print(self.unique_tools_dataset)
|
| 793 |
+
#############################
|
| 794 |
+
|
| 795 |
+
#############################
|
| 796 |
+
# DatasetDict #
|
| 797 |
+
# with multiple tables #
|
| 798 |
+
#############################
|
| 799 |
+
dataset_dict = DatasetDict({
|
| 800 |
+
"continued_pre_training": \
|
| 801 |
+
self.unique_tools_dataset,
|
| 802 |
+
"supervised_finetuning": sft_dataset
|
| 803 |
+
})
|
| 804 |
+
print(dataset_dict, flush=True)
|
| 805 |
+
#############################
|
| 806 |
+
|
| 807 |
+
#############################
|
| 808 |
+
# dataset README #
|
| 809 |
+
# from template #
|
| 810 |
+
#############################
|
| 811 |
+
commit_datetime = datetime.utcnow()
|
| 812 |
+
new_dataset_version_label = get_new_repo_minor_version(
|
| 813 |
+
repo_id=self.dataset_repo_id,
|
| 814 |
+
repo_type="dataset",
|
| 815 |
+
hf_token=os.getenv("HF_TOKEN", None))
|
| 816 |
+
readme_content = get_dataset_readme_content(
|
| 817 |
+
template_folder=template_dir,
|
| 818 |
+
|
| 819 |
+
hf_dataset_dict=self.hf_dataset_dict,
|
| 820 |
+
hf_enrich_dataset_dict=self.hf_enrich_dataset_dict,
|
| 821 |
+
dataset_dict=dataset_dict,
|
| 822 |
+
|
| 823 |
+
augmentation_rate=self.actual_augmentation_rate,
|
| 824 |
+
enrichment_rate=self.enrichment_rate,
|
| 825 |
+
|
| 826 |
+
version_label=new_dataset_version_label,
|
| 827 |
+
commit_datetime=commit_datetime,
|
| 828 |
+
|
| 829 |
+
mf_flow_name=current.flow_name,
|
| 830 |
+
mf_run_id=current.run.id,
|
| 831 |
+
engine=self.engine
|
| 832 |
+
)
|
| 833 |
+
#############################
|
| 834 |
+
|
| 835 |
+
dataset_commit_hash = push_dataset_version_to_hub(
|
| 836 |
+
repo_id=self.dataset_repo_id,
|
| 837 |
+
version_label=new_dataset_version_label,
|
| 838 |
+
timestamp_str=commit_datetime.strftime(
|
| 839 |
+
"%Y-%m-%d %H:%M:%S UTC"),
|
| 840 |
+
dataset_dict=dataset_dict,
|
| 841 |
+
dataset_readme_content=readme_content,
|
| 842 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 843 |
+
)
|
| 844 |
+
if not dataset_commit_hash:
|
| 845 |
+
raise Exception(
|
| 846 |
+
"Failed to publish dataset version.")
|
| 847 |
+
print(f"https://huggingface.co/datasets/{self.dataset_repo_id}" +
|
| 848 |
+
f"/blob/{dataset_commit_hash}/README.md")
|
| 849 |
+
self.dataset_commit_dict = {
|
| 850 |
+
"repo_id": self.dataset_repo_id,
|
| 851 |
+
"commit_hash": dataset_commit_hash,
|
| 852 |
+
"version_label": new_dataset_version_label,
|
| 853 |
+
"commit_datetime": commit_datetime,
|
| 854 |
+
}
|
| 855 |
+
|
| 856 |
+
self.next(self.continued_pre_training)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
@step
|
| 860 |
+
def continued_pre_training(self):
|
| 861 |
+
"""
|
| 862 |
+
Gives the base model some additional intrinsic knowkledge
|
| 863 |
+
through continued pre-training.
|
| 864 |
+
See unsloth.ai/blog/contpretraining
|
| 865 |
+
"""
|
| 866 |
+
from retrain_pipelines.model.hf_utils import \
|
| 867 |
+
plot_log_history
|
| 868 |
+
|
| 869 |
+
#######################################
|
| 870 |
+
# base-model and associated tokenizer #
|
| 871 |
+
# from Hub (or local cache) #
|
| 872 |
+
#######################################
|
| 873 |
+
self.max_seq_length = 2048
|
| 874 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 875 |
+
model_name=self.hf_base_model_dict["repo_id"],
|
| 876 |
+
revision=self.hf_base_model_dict["commit_hash"],
|
| 877 |
+
max_seq_length=self.max_seq_length,
|
| 878 |
+
dtype=None,
|
| 879 |
+
load_in_4bit=False,
|
| 880 |
+
# case of a gated or private base-model
|
| 881 |
+
token=os.getenv("HF_TOKEN", None)
|
| 882 |
+
)
|
| 883 |
+
#######################################
|
| 884 |
+
|
| 885 |
+
#######################################
|
| 886 |
+
# dataset prompt_template mapping #
|
| 887 |
+
#######################################
|
| 888 |
+
tools_dataset = DatasetDict(
|
| 889 |
+
{"train": self.unique_tools_dataset})
|
| 890 |
+
print(tools_dataset)
|
| 891 |
+
tool_prompt_template = "tool: {}"
|
| 892 |
+
def formatting_prompts_func(tools_batch):
|
| 893 |
+
tools_batch = tools_batch["tool"]
|
| 894 |
+
outputs = []
|
| 895 |
+
for tool in tools_batch:
|
| 896 |
+
# Must add EOS_TOKEN,
|
| 897 |
+
# otherwise generation will go on forever!
|
| 898 |
+
text = tool_prompt_template.format(tool) + \
|
| 899 |
+
tokenizer.eos_token
|
| 900 |
+
outputs.append(text)
|
| 901 |
+
return { "tools" : outputs, }
|
| 902 |
+
cpt_dataset = tools_dataset["train"].map(
|
| 903 |
+
formatting_prompts_func, batched=True,)
|
| 904 |
+
#######################################
|
| 905 |
+
|
| 906 |
+
#######################################
|
| 907 |
+
# PEFT adapter #
|
| 908 |
+
# for continued pre-training #
|
| 909 |
+
#######################################
|
| 910 |
+
model = FastLanguageModel.get_peft_model(
|
| 911 |
+
model,
|
| 912 |
+
r = 128, # any number >0 ; 8, 16, 32, 64, 128, 256
|
| 913 |
+
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
|
| 914 |
+
"gate_proj", "up_proj", "down_proj",
|
| 915 |
+
# Add for continued pretraining
|
| 916 |
+
"embed_tokens", "lm_head",],
|
| 917 |
+
lora_alpha = 32,
|
| 918 |
+
lora_dropout = 0, # Supports any, 0 is optimized
|
| 919 |
+
bias = "none", # Supports any, "none" is optimized
|
| 920 |
+
# True or "unsloth" for very long context
|
| 921 |
+
use_gradient_checkpointing = "unsloth",
|
| 922 |
+
use_rslora = True, # rank-stabilized LoRA
|
| 923 |
+
loftq_config = None, # LoftQ
|
| 924 |
+
#random_state = 3407,
|
| 925 |
+
)
|
| 926 |
+
#######################################
|
| 927 |
+
|
| 928 |
+
#######################################
|
| 929 |
+
# cpt_trainer #
|
| 930 |
+
#######################################
|
| 931 |
+
if (
|
| 932 |
+
"records_cap" in self.cpt_training_args and
|
| 933 |
+
self.cpt_training_args["records_cap"] is not None and
|
| 934 |
+
isinstance(self.cpt_training_args["records_cap"], int)
|
| 935 |
+
):
|
| 936 |
+
cpt_dataset = cpt_dataset.take(
|
| 937 |
+
self.cpt_training_args["records_cap"])
|
| 938 |
+
print(f"cpt_dataset : {cpt_dataset}")
|
| 939 |
+
|
| 940 |
+
train_args = UnslothTrainingArguments(
|
| 941 |
+
# https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.save_strategy
|
| 942 |
+
per_device_train_batch_size=2,
|
| 943 |
+
gradient_accumulation_steps=8,
|
| 944 |
+
|
| 945 |
+
**{k: v for k, v in self.cpt_training_args.items()
|
| 946 |
+
if k != "records_cap"},
|
| 947 |
+
|
| 948 |
+
# 2 to 10x smaller learning rate
|
| 949 |
+
# for the embedding matrices
|
| 950 |
+
learning_rate=5e-5,
|
| 951 |
+
embedding_learning_rate=1e-5,
|
| 952 |
+
|
| 953 |
+
fp16=not is_bfloat16_supported(),
|
| 954 |
+
bf16=is_bfloat16_supported(),
|
| 955 |
+
logging_steps=1,
|
| 956 |
+
optim="adamw_8bit",
|
| 957 |
+
weight_decay=0.01,
|
| 958 |
+
lr_scheduler_type="linear",
|
| 959 |
+
#seed=3407,
|
| 960 |
+
|
| 961 |
+
output_dir=os.path.join(
|
| 962 |
+
self.unsloth_dir, "outputs", "cpt"),
|
| 963 |
+
save_total_limit = 2,
|
| 964 |
+
|
| 965 |
+
report_to="tensorboard",
|
| 966 |
+
logging_dir=os.path.join(
|
| 967 |
+
self.sft_model_dir,
|
| 968 |
+
"runs", "cpt")
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
self.cpt_traces_file_fullname = os.path.join(
|
| 972 |
+
self.unsloth_dir, "cpt_trainer_traces.txt")
|
| 973 |
+
print("Training started. " +
|
| 974 |
+
f"Check {self.cpt_traces_file_fullname} for live traces.",
|
| 975 |
+
flush=True)
|
| 976 |
+
|
| 977 |
+
trainer = UnslothTrainer(
|
| 978 |
+
model=model, tokenizer=tokenizer,
|
| 979 |
+
train_dataset=cpt_dataset,
|
| 980 |
+
dataset_text_field="tools",
|
| 981 |
+
max_seq_length=self.max_seq_length,
|
| 982 |
+
dataset_num_proc=2,
|
| 983 |
+
args=train_args,
|
| 984 |
+
)
|
| 985 |
+
#######################################
|
| 986 |
+
|
| 987 |
+
#######################################
|
| 988 |
+
# Show current memory stats #
|
| 989 |
+
#######################################
|
| 990 |
+
torch.cuda.ipc_collect()
|
| 991 |
+
torch.cuda.empty_cache()
|
| 992 |
+
gc.collect()
|
| 993 |
+
|
| 994 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
| 995 |
+
self.start_gpu_memory = \
|
| 996 |
+
round(torch.cuda.max_memory_reserved()
|
| 997 |
+
/ 1024 / 1024 / 1024, 3)
|
| 998 |
+
self.max_memory = \
|
| 999 |
+
round(gpu_stats.total_memory
|
| 1000 |
+
/ 1024 / 1024 / 1024, 3)
|
| 1001 |
+
print(f"GPU = {gpu_stats.name}. " +
|
| 1002 |
+
f"Max memory = {self.max_memory} GB.")
|
| 1003 |
+
print(f"{self.start_gpu_memory} GB of memory reserved.")
|
| 1004 |
+
#######################################
|
| 1005 |
+
|
| 1006 |
+
with open(self.cpt_traces_file_fullname, 'w') as f:
|
| 1007 |
+
with redirect_stdout(f):
|
| 1008 |
+
hf_logging.set_verbosity_error()
|
| 1009 |
+
hf_logging.disable_progress_bar()
|
| 1010 |
+
trainer_stats = trainer.train()
|
| 1011 |
+
hf_logging.set_verbosity_info()
|
| 1012 |
+
hf_logging.enable_progress_bar()
|
| 1013 |
+
print(f"{trainer_stats.metrics['train_runtime']} " +
|
| 1014 |
+
f"seconds used for training " +
|
| 1015 |
+
f"({round(trainer_stats.metrics['train_runtime']/60, 2)}" +
|
| 1016 |
+
f" minutes).")
|
| 1017 |
+
|
| 1018 |
+
self.cpt_log_history = trainer.state.log_history
|
| 1019 |
+
# print(self.cpt_log_history)
|
| 1020 |
+
self.cpt_log_history_fig = \
|
| 1021 |
+
plot_log_history(
|
| 1022 |
+
self.cpt_log_history,
|
| 1023 |
+
title="Continued pretraining loss"
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
model.save_pretrained_merged(
|
| 1027 |
+
save_directory=self.cpt_model_dir,
|
| 1028 |
+
tokenizer=tokenizer,
|
| 1029 |
+
save_method="lora"
|
| 1030 |
+
)
|
| 1031 |
+
print(f"cpt_model_dir : {self.cpt_model_dir}\n")
|
| 1032 |
+
|
| 1033 |
+
self.next(self.supervised_finetuning)
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
@step
|
| 1037 |
+
def supervised_finetuning(self):
|
| 1038 |
+
"""
|
| 1039 |
+
Trains the model on tool-calling
|
| 1040 |
+
task specialization.
|
| 1041 |
+
"""
|
| 1042 |
+
from retrain_pipelines.model.hf_utils import \
|
| 1043 |
+
plot_log_history
|
| 1044 |
+
|
| 1045 |
+
torch.cuda.ipc_collect()
|
| 1046 |
+
torch.cuda.empty_cache()
|
| 1047 |
+
gc.collect()
|
| 1048 |
+
|
| 1049 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 1050 |
+
model_name=self.cpt_model_dir,
|
| 1051 |
+
max_seq_length=self.max_seq_length,
|
| 1052 |
+
dtype=None,
|
| 1053 |
+
load_in_4bit=False,
|
| 1054 |
+
)
|
| 1055 |
+
# !!!! bug fix BEGIN !!!!
|
| 1056 |
+
# otherwise, 'embed_tokens' and 'lm_head'
|
| 1057 |
+
# trained during CPT are "ignored",
|
| 1058 |
+
# i.e. not saved after SFT
|
| 1059 |
+
# (note that, alternatively, we could also
|
| 1060 |
+
# do this fix after sft-training and
|
| 1061 |
+
# just before saving ;
|
| 1062 |
+
# which would be equivalent to
|
| 1063 |
+
# freezing embeddings during finetuning
|
| 1064 |
+
# for better pretrained knowledge retention)
|
| 1065 |
+
# @see https://www.reddit.com/r/unsloth/comments/1dtzcd6/fastlanguagemodelpatch_peft_model_changing/
|
| 1066 |
+
model.model.model.embed_tokens.modules_to_save.default.to(
|
| 1067 |
+
device="cuda:0",
|
| 1068 |
+
dtype=torch.float32,
|
| 1069 |
+
non_blocking=True)
|
| 1070 |
+
model.model.model.embed_tokens.modules_to_save.default \
|
| 1071 |
+
.requires_grad_(True)
|
| 1072 |
+
model.model.lm_head.modules_to_save.default.to(
|
| 1073 |
+
device="cuda:0",
|
| 1074 |
+
dtype=torch.float32,
|
| 1075 |
+
non_blocking=True)
|
| 1076 |
+
model.model.lm_head.modules_to_save.default \
|
| 1077 |
+
.requires_grad_(True)
|
| 1078 |
+
# !!!! bug fix END !!!!
|
| 1079 |
+
|
| 1080 |
+
#######################################
|
| 1081 |
+
# dataset prompt_template mapping #
|
| 1082 |
+
#######################################
|
| 1083 |
+
# download from Hub (or get from local cache)
|
| 1084 |
+
queries_dataset = load_dataset(
|
| 1085 |
+
path=self.dataset_commit_dict["repo_id"],
|
| 1086 |
+
name="supervised_finetuning",
|
| 1087 |
+
revision=self.dataset_commit_dict["commit_hash"],
|
| 1088 |
+
token=os.getenv("HF_TOKEN", None))
|
| 1089 |
+
print(f"HF_DATASETS_CACHE : {HF_DATASETS_CACHE}") # HF_CACHE_HOME
|
| 1090 |
+
self.sft_prompt_template = dedent("""
|
| 1091 |
+
You specialize in generating tool calls. Given a query, your task is to return a list of tool calls based on your knowledge of known tools.
|
| 1092 |
+
|
| 1093 |
+
Rules:
|
| 1094 |
+
1. You can only use tools you know. Do not create new tools under any circumstances.
|
| 1095 |
+
2. If a query does not match any known tool, return an empty list ([]).
|
| 1096 |
+
3. If information is missing to use a known tool, do not attempt to use it.
|
| 1097 |
+
4. Your response must always be a valid JSON array, and nothing else.
|
| 1098 |
+
|
| 1099 |
+
Be precise and do not guess.
|
| 1100 |
+
|
| 1101 |
+
# query:
|
| 1102 |
+
{}
|
| 1103 |
+
# response:
|
| 1104 |
+
{}
|
| 1105 |
+
""").strip()
|
| 1106 |
+
tokenizer.chat_template = self.sft_prompt_template
|
| 1107 |
+
|
| 1108 |
+
EOS_TOKEN = tokenizer.eos_token
|
| 1109 |
+
def formatting_prompts_func(records):
|
| 1110 |
+
query = records["query"]
|
| 1111 |
+
tools = records["answers"]
|
| 1112 |
+
outputs = []
|
| 1113 |
+
for query, tools in zip(query, tools):
|
| 1114 |
+
# Must add EOS_TOKEN,
|
| 1115 |
+
# otherwise your generation will go on forever
|
| 1116 |
+
text = self.sft_prompt_template.format(query, tools) \
|
| 1117 |
+
+ EOS_TOKEN
|
| 1118 |
+
outputs.append(text)
|
| 1119 |
+
return { "text" : outputs, }
|
| 1120 |
+
sft_train_dataset = queries_dataset["train"].map(
|
| 1121 |
+
formatting_prompts_func, batched=True)
|
| 1122 |
+
sft_valid_dataset = queries_dataset["validation"].map(
|
| 1123 |
+
formatting_prompts_func, batched=True,)
|
| 1124 |
+
#######################################
|
| 1125 |
+
|
| 1126 |
+
#######################################
|
| 1127 |
+
# PEFT adapter #
|
| 1128 |
+
# for supervised finetuning #
|
| 1129 |
+
#######################################
|
| 1130 |
+
# for cases where CPT has been merged into overall model
|
| 1131 |
+
# otherwize, keep on training current LoRa adapter
|
| 1132 |
+
# model = FastLanguageModel.get_peft_model(
|
| 1133 |
+
# model,
|
| 1134 |
+
# r = 128, # any number >0 ; 8, 16, 32, 64, 128, 256
|
| 1135 |
+
# target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
|
| 1136 |
+
# "gate_proj", "up_proj", "down_proj"],
|
| 1137 |
+
# lora_alpha = 32,
|
| 1138 |
+
# lora_dropout = 0, # Supports any, but = 0 is optimized
|
| 1139 |
+
# bias = "none", # Supports any, but = "none" is optimized
|
| 1140 |
+
# # True or "unsloth" for very long context
|
| 1141 |
+
# use_gradient_checkpointing = "unsloth",
|
| 1142 |
+
# random_state = 3407,
|
| 1143 |
+
# use_rslora = True, # rank stabilized LoRA
|
| 1144 |
+
# loftq_config = None, # LoftQ
|
| 1145 |
+
# )
|
| 1146 |
+
#######################################
|
| 1147 |
+
|
| 1148 |
+
#######################################
|
| 1149 |
+
# sft_trainer #
|
| 1150 |
+
#######################################
|
| 1151 |
+
split = sft_train_dataset.train_test_split(
|
| 1152 |
+
test_size=1000,
|
| 1153 |
+
#seed=42
|
| 1154 |
+
)
|
| 1155 |
+
train_dataset = split['train']
|
| 1156 |
+
eval_dataset = split['test']
|
| 1157 |
+
if (
|
| 1158 |
+
"records_cap" in self.sft_training_args and
|
| 1159 |
+
self.sft_training_args["records_cap"] is not None and
|
| 1160 |
+
isinstance(self.sft_training_args["records_cap"], int)
|
| 1161 |
+
):
|
| 1162 |
+
train_dataset = train_dataset.take(
|
| 1163 |
+
self.sft_training_args["records_cap"])
|
| 1164 |
+
eval_dataset = eval_dataset.take(
|
| 1165 |
+
self.sft_training_args["records_cap"])
|
| 1166 |
+
print(f"train_dataset : {train_dataset}")
|
| 1167 |
+
print(f"eval_dataset : {eval_dataset}")
|
| 1168 |
+
|
| 1169 |
+
train_args = UnslothTrainingArguments(
|
| 1170 |
+
per_device_train_batch_size=2,
|
| 1171 |
+
gradient_accumulation_steps=8,
|
| 1172 |
+
|
| 1173 |
+
**{k: v for k, v in self.sft_training_args.items()
|
| 1174 |
+
if k != "records_cap"},
|
| 1175 |
+
|
| 1176 |
+
per_device_eval_batch_size=2,
|
| 1177 |
+
eval_steps=200,
|
| 1178 |
+
eval_strategy="steps",
|
| 1179 |
+
do_eval=True,
|
| 1180 |
+
|
| 1181 |
+
learning_rate=5e-5,
|
| 1182 |
+
# embedding_learning_rate=1e-5, # Optionally here
|
| 1183 |
+
|
| 1184 |
+
fp16=not is_bfloat16_supported(),
|
| 1185 |
+
bf16=is_bfloat16_supported(),
|
| 1186 |
+
|
| 1187 |
+
optim="adamw_8bit",
|
| 1188 |
+
weight_decay=0.00,
|
| 1189 |
+
lr_scheduler_type="linear",
|
| 1190 |
+
#seed=3407,
|
| 1191 |
+
|
| 1192 |
+
output_dir=os.path.join(
|
| 1193 |
+
self.unsloth_dir, "outputs", "sft"),
|
| 1194 |
+
save_total_limit=2,
|
| 1195 |
+
|
| 1196 |
+
logging_steps=1,
|
| 1197 |
+
report_to="tensorboard",
|
| 1198 |
+
logging_dir=os.path.join(
|
| 1199 |
+
self.sft_model_dir,
|
| 1200 |
+
"runs", "sft")
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
self.sft_traces_file_fullname = os.path.join(
|
| 1204 |
+
self.unsloth_dir, "sft_trainer_traces.txt")
|
| 1205 |
+
print("Training started. " +
|
| 1206 |
+
f"Check {self.sft_traces_file_fullname} for live traces.",
|
| 1207 |
+
flush=True)
|
| 1208 |
+
|
| 1209 |
+
trainer = UnslothTrainer(
|
| 1210 |
+
model=model, tokenizer=tokenizer,
|
| 1211 |
+
train_dataset=train_dataset,
|
| 1212 |
+
dataset_text_field="text",
|
| 1213 |
+
eval_dataset=eval_dataset,
|
| 1214 |
+
max_seq_length=self.max_seq_length,
|
| 1215 |
+
dataset_num_proc=8,
|
| 1216 |
+
args=train_args
|
| 1217 |
+
)
|
| 1218 |
+
trainer.can_return_loss = True
|
| 1219 |
+
#######################################
|
| 1220 |
+
|
| 1221 |
+
#######################################
|
| 1222 |
+
# Show current memory stats #
|
| 1223 |
+
#######################################
|
| 1224 |
+
torch.cuda.ipc_collect()
|
| 1225 |
+
torch.cuda.empty_cache()
|
| 1226 |
+
gc.collect()
|
| 1227 |
+
|
| 1228 |
+
used_memory = \
|
| 1229 |
+
round(torch.cuda.max_memory_reserved()
|
| 1230 |
+
/1024/1024/1024, 3)
|
| 1231 |
+
used_memory_for_lora = \
|
| 1232 |
+
round(used_memory-self.start_gpu_memory, 3)
|
| 1233 |
+
used_percentage = \
|
| 1234 |
+
round(used_memory/self.max_memory*100, 3)
|
| 1235 |
+
lora_percentage = \
|
| 1236 |
+
round(used_memory_for_lora/self.max_memory*100,
|
| 1237 |
+
3)
|
| 1238 |
+
print(f"Peak reserved memory = " +
|
| 1239 |
+
f"{used_memory} GB.")
|
| 1240 |
+
print(f"Peak reserved memory for " +
|
| 1241 |
+
f"training = {used_memory_for_lora} " +
|
| 1242 |
+
f"GB.")
|
| 1243 |
+
print(f"Peak reserved memory % of " +
|
| 1244 |
+
f"max memory = {used_percentage} %.")
|
| 1245 |
+
print(f"Peak reserved memory for training " +
|
| 1246 |
+
f"% of max memory = {lora_percentage} %.")
|
| 1247 |
+
#######################################
|
| 1248 |
+
|
| 1249 |
+
with open(self.sft_traces_file_fullname, 'w') as f:
|
| 1250 |
+
with redirect_stdout(f):
|
| 1251 |
+
hf_logging.set_verbosity_error()
|
| 1252 |
+
hf_logging.disable_progress_bar()
|
| 1253 |
+
trainer_stats = trainer.train()
|
| 1254 |
+
hf_logging.set_verbosity_info()
|
| 1255 |
+
hf_logging.enable_progress_bar()
|
| 1256 |
+
print(f"{trainer_stats.metrics['train_runtime']} " +
|
| 1257 |
+
f"seconds used for training " +
|
| 1258 |
+
f"({round(trainer_stats.metrics['train_runtime']/60, 2)}" +
|
| 1259 |
+
f" minutes).")
|
| 1260 |
+
|
| 1261 |
+
self.sft_log_history = trainer.state.log_history
|
| 1262 |
+
self.sft_log_history_fig = \
|
| 1263 |
+
plot_log_history(
|
| 1264 |
+
self.sft_log_history,
|
| 1265 |
+
title="Supervised finetuning loss"
|
| 1266 |
+
)
|
| 1267 |
+
|
| 1268 |
+
model.save_pretrained_merged(
|
| 1269 |
+
self.sft_model_dir, tokenizer,
|
| 1270 |
+
save_method = "lora"
|
| 1271 |
+
)
|
| 1272 |
+
print(f"sft_model_dir : {self.sft_model_dir}\n")
|
| 1273 |
+
|
| 1274 |
+
self.next(self.evaluate_model)
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
@step
|
| 1278 |
+
def evaluate_model(self):
|
| 1279 |
+
"""
|
| 1280 |
+
Batch inference on the SFT validation dataset.
|
| 1281 |
+
"""
|
| 1282 |
+
from retrain_pipelines.model import \
|
| 1283 |
+
infer_validation, compute_counts_n_metrics, \
|
| 1284 |
+
plot_validation_completions
|
| 1285 |
+
|
| 1286 |
+
torch.cuda.ipc_collect()
|
| 1287 |
+
torch.cuda.empty_cache()
|
| 1288 |
+
gc.collect()
|
| 1289 |
+
|
| 1290 |
+
|
| 1291 |
+
######################################################
|
| 1292 |
+
# loading trained adapter #
|
| 1293 |
+
######################################################
|
| 1294 |
+
# Unsloth (if loading both model & tokenizer at once #
|
| 1295 |
+
# same as we did in prior tasks, but now #
|
| 1296 |
+
# with tokenizer.chat_template being set #
|
| 1297 |
+
# in tokenizer.config) is forcing on us some kind of #
|
| 1298 |
+
# chat_template format hard-requirements #
|
| 1299 |
+
# coming from their dream-fantasmagorical world.. #
|
| 1300 |
+
######################################################
|
| 1301 |
+
# load base from cache
|
| 1302 |
+
# (with base tokenizer, which we ignore)
|
| 1303 |
+
model, _ = FastLanguageModel.from_pretrained(
|
| 1304 |
+
model_name=self.hf_base_model_dict["repo_id"],
|
| 1305 |
+
revision=self.hf_base_model_dict["commit_hash"],
|
| 1306 |
+
max_seq_length=self.max_seq_length,
|
| 1307 |
+
dtype=None,
|
| 1308 |
+
load_in_4bit=False,
|
| 1309 |
+
# case of a gated or private base-model
|
| 1310 |
+
token=os.getenv("HF_TOKEN", None)
|
| 1311 |
+
)
|
| 1312 |
+
model = FastLanguageModel.for_inference(model)
|
| 1313 |
+
# load our CPT+SFT trained & locally-saved adapter
|
| 1314 |
+
model.load_adapter(peft_model_id=self.sft_model_dir)
|
| 1315 |
+
# Separately load our (potentially trained &)
|
| 1316 |
+
# locally-saved adapter-tokenizer
|
| 1317 |
+
# (loading it below via HF and not Unsloth)
|
| 1318 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 1319 |
+
pretrained_model_name_or_path=self.sft_model_dir
|
| 1320 |
+
)
|
| 1321 |
+
######################################################
|
| 1322 |
+
|
| 1323 |
+
######################################################
|
| 1324 |
+
# validation dataset #
|
| 1325 |
+
######################################################
|
| 1326 |
+
# download from Hub (or get from local cache)
|
| 1327 |
+
queries_dataset = load_dataset(
|
| 1328 |
+
path=self.dataset_commit_dict["repo_id"],
|
| 1329 |
+
name="supervised_finetuning",
|
| 1330 |
+
revision=self.dataset_commit_dict["commit_hash"],
|
| 1331 |
+
token=os.getenv("HF_TOKEN", None))
|
| 1332 |
+
if (
|
| 1333 |
+
"records_cap" in self.sft_training_args and
|
| 1334 |
+
self.sft_training_args["records_cap"] is not None and
|
| 1335 |
+
isinstance(self.sft_training_args["records_cap"], int)
|
| 1336 |
+
):
|
| 1337 |
+
validation_data = queries_dataset["validation"].take(
|
| 1338 |
+
self.sft_training_args["records_cap"])
|
| 1339 |
+
else:
|
| 1340 |
+
validation_data = queries_dataset["validation"]
|
| 1341 |
+
print(validation_data)
|
| 1342 |
+
######################################################
|
| 1343 |
+
|
| 1344 |
+
self.max_new_tokens = 400
|
| 1345 |
+
start_time = time.time()
|
| 1346 |
+
validation_results = infer_validation(
|
| 1347 |
+
tokenizer=tokenizer,
|
| 1348 |
+
model=model,
|
| 1349 |
+
validation_data=validation_data,
|
| 1350 |
+
prompt_template=tokenizer.chat_template,
|
| 1351 |
+
batch_size=32, # 64,
|
| 1352 |
+
queries_attr_name=\
|
| 1353 |
+
self.hf_dataset["attributes"]["query_attr"],
|
| 1354 |
+
answers_attr_name=\
|
| 1355 |
+
self.hf_dataset["attributes"]["answers_attr"],
|
| 1356 |
+
max_new_tokens=self.max_new_tokens,
|
| 1357 |
+
device="cuda"
|
| 1358 |
+
)
|
| 1359 |
+
print("infer_validation - Elapsed time: " +
|
| 1360 |
+
f"{(time.time() - start_time):.2f} seconds")
|
| 1361 |
+
self.validation_results = validation_results # <= to artifacts store
|
| 1362 |
+
|
| 1363 |
+
eval_df = pl.LazyFrame(validation_results)
|
| 1364 |
+
|
| 1365 |
+
records = eval_df.with_columns(
|
| 1366 |
+
(pl.col("answer") == pl.col("completion")) \
|
| 1367 |
+
.alias("is_ground_truth_identical")
|
| 1368 |
+
).collect() #engine=self.engine)
|
| 1369 |
+
print("perfect characters-match accuracy : " +
|
| 1370 |
+
str(records['is_ground_truth_identical'].mean()))
|
| 1371 |
+
|
| 1372 |
+
eval_metrics_df = compute_counts_n_metrics(
|
| 1373 |
+
eval_df, is_format_fault_tolerant=True)
|
| 1374 |
+
overall_metrics_df = eval_metrics_df.select([
|
| 1375 |
+
pl.col("precision").mean(),
|
| 1376 |
+
pl.col("recall").mean(),
|
| 1377 |
+
pl.col("f1").mean(),
|
| 1378 |
+
pl.col("jaccard").mean()
|
| 1379 |
+
]).collect() #engine=self.engine)
|
| 1380 |
+
self.perf_metrics = overall_metrics_df.row(0, named=True)
|
| 1381 |
+
print(self.perf_metrics)
|
| 1382 |
+
|
| 1383 |
+
self.validation_completions_fig = \
|
| 1384 |
+
plot_validation_completions(
|
| 1385 |
+
eval_metrics_df, engine=self.engine)
|
| 1386 |
+
|
| 1387 |
+
del model
|
| 1388 |
+
del tokenizer
|
| 1389 |
+
torch.cuda.ipc_collect()
|
| 1390 |
+
torch.cuda.empty_cache()
|
| 1391 |
+
gc.collect()
|
| 1392 |
+
|
| 1393 |
+
self.next(self.model_version_blessing)
|
| 1394 |
+
|
| 1395 |
+
|
| 1396 |
+
@step
|
| 1397 |
+
def model_version_blessing(self):
|
| 1398 |
+
"""
|
| 1399 |
+
"""
|
| 1400 |
+
from retrain_pipelines.model.hf_utils import \
|
| 1401 |
+
current_blessed_model_version_dict
|
| 1402 |
+
|
| 1403 |
+
main_perf_metric_name = "jaccard"
|
| 1404 |
+
|
| 1405 |
+
current_blessed_version_dict = \
|
| 1406 |
+
current_blessed_model_version_dict(
|
| 1407 |
+
repo_id=self.model_repo_id,
|
| 1408 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 1409 |
+
)
|
| 1410 |
+
print("current_blessed_version_dict : " +
|
| 1411 |
+
str(current_blessed_version_dict))
|
| 1412 |
+
|
| 1413 |
+
if current_blessed_version_dict is None:
|
| 1414 |
+
print("case 'no prior blessed model version found"
|
| 1415 |
+
" => blessing.'")
|
| 1416 |
+
self.model_version_blessed = True
|
| 1417 |
+
|
| 1418 |
+
elif (
|
| 1419 |
+
main_perf_metric_name in
|
| 1420 |
+
current_blessed_version_dict["perf_metrics"]
|
| 1421 |
+
):
|
| 1422 |
+
current_blessed_run_id = \
|
| 1423 |
+
current_blessed_version_dict["mf_run_id"]
|
| 1424 |
+
current_blessed_metric_value = \
|
| 1425 |
+
current_blessed_version_dict[
|
| 1426 |
+
"perf_metrics"][main_perf_metric_name]
|
| 1427 |
+
|
| 1428 |
+
self.model_version_blessed = (
|
| 1429 |
+
self.perf_metrics[main_perf_metric_name] >=
|
| 1430 |
+
current_blessed_metric_value
|
| 1431 |
+
)
|
| 1432 |
+
|
| 1433 |
+
if not self.model_version_blessed:
|
| 1434 |
+
self.current_blessed_version_dict = \
|
| 1435 |
+
current_blessed_version_dict
|
| 1436 |
+
for run in Flow(self.__class__.__name__):
|
| 1437 |
+
if (
|
| 1438 |
+
str(run.id) == current_blessed_run_id and
|
| 1439 |
+
True
|
| 1440 |
+
):
|
| 1441 |
+
self.current_blessed_run = run
|
| 1442 |
+
break
|
| 1443 |
+
## DEBUG
|
| 1444 |
+
print(run)
|
| 1445 |
+
print(dir(run))
|
| 1446 |
+
print(help(run.steps))
|
| 1447 |
+
print(run.steps())
|
| 1448 |
+
print(run.steps()[0])
|
| 1449 |
+
raise Exception("DEBUG")
|
| 1450 |
+
## DEBUG
|
| 1451 |
+
if not self.current_blessed_run:
|
| 1452 |
+
print(
|
| 1453 |
+
"Couldn't find blessed run " +
|
| 1454 |
+
f"{current_blessed_run_id} !\n" +
|
| 1455 |
+
"It seems that prior blessed run was " +
|
| 1456 |
+
"executed on another ML framework instance.",
|
| 1457 |
+
file=sys.stderr, flush=True)
|
| 1458 |
+
|
| 1459 |
+
print("new : " +
|
| 1460 |
+
str(self.perf_metrics[main_perf_metric_name]) +
|
| 1461 |
+
" - previous best : " +
|
| 1462 |
+
str(current_blessed_metric_value) +
|
| 1463 |
+
" - model_version_blessing : " +
|
| 1464 |
+
str(self.model_version_blessed))
|
| 1465 |
+
|
| 1466 |
+
else:
|
| 1467 |
+
raise Exception(
|
| 1468 |
+
"Performance metric '" +
|
| 1469 |
+
main_perf_metric_name +
|
| 1470 |
+
"' can't be found in eval results " +
|
| 1471 |
+
"from blessed run " +
|
| 1472 |
+
str(current_blessed_version_dict[
|
| 1473 |
+
"mf_run_id"]) + " !")
|
| 1474 |
+
|
| 1475 |
+
# self.model_version_blessed = True ### DEBUG - DELETE ###
|
| 1476 |
+
|
| 1477 |
+
self.next(self.model_to_hub)
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
@step
|
| 1481 |
+
def model_to_hub(self):
|
| 1482 |
+
"""
|
| 1483 |
+
Push to hub model version, including
|
| 1484 |
+
readme with versioning info.
|
| 1485 |
+
"""
|
| 1486 |
+
|
| 1487 |
+
#############################
|
| 1488 |
+
# case of user-provided #
|
| 1489 |
+
# documentation artifact(s) #
|
| 1490 |
+
#############################
|
| 1491 |
+
# note that user can provide either
|
| 1492 |
+
# 'pipeline_card.py' or 'template.html'
|
| 1493 |
+
# or 'dataset_readme.py'
|
| 1494 |
+
# or 'dataset_readme_template.md'
|
| 1495 |
+
# or 'model_readme.py'
|
| 1496 |
+
# or 'model_readme_template.md'
|
| 1497 |
+
# or any combination of those
|
| 1498 |
+
# when specifying custom
|
| 1499 |
+
# 'pipeline_card_artifacts_path'
|
| 1500 |
+
if (
|
| 1501 |
+
"model_readme_template.md" in
|
| 1502 |
+
os.listdir(self.pipeline_card_artifacts_path)
|
| 1503 |
+
):
|
| 1504 |
+
template_dir = self.pipeline_card_artifacts_path
|
| 1505 |
+
else:
|
| 1506 |
+
template_dir = os.path.dirname(
|
| 1507 |
+
importlib.util.find_spec(
|
| 1508 |
+
f"retrain_pipelines.pipeline_card."+
|
| 1509 |
+
f"{os.getenv('retrain_pipeline_type')}"
|
| 1510 |
+
).origin)
|
| 1511 |
+
print(f"template_dir : '{template_dir}'")
|
| 1512 |
+
#############################
|
| 1513 |
+
if "model_readme.py" in os.listdir(
|
| 1514 |
+
self.pipeline_card_artifacts_path):
|
| 1515 |
+
from retrain_pipelines.utils import \
|
| 1516 |
+
get_get_model_readme_content
|
| 1517 |
+
get_model_readme_content = \
|
| 1518 |
+
get_get_model_readme_content(
|
| 1519 |
+
self.pipeline_card_artifacts_path)
|
| 1520 |
+
else:
|
| 1521 |
+
from retrain_pipelines.pipeline_card import \
|
| 1522 |
+
get_model_readme_content
|
| 1523 |
+
#############################
|
| 1524 |
+
from retrain_pipelines.model.hf_utils import \
|
| 1525 |
+
push_model_version_to_hub
|
| 1526 |
+
|
| 1527 |
+
#############################
|
| 1528 |
+
# model README #
|
| 1529 |
+
# from template #
|
| 1530 |
+
#############################
|
| 1531 |
+
commit_datetime = datetime.utcnow()
|
| 1532 |
+
new_model_version_label = get_new_repo_minor_version(
|
| 1533 |
+
repo_id=self.model_repo_id,
|
| 1534 |
+
repo_type="model",
|
| 1535 |
+
hf_token=os.getenv("HF_TOKEN", None))
|
| 1536 |
+
readme_content = get_model_readme_content(
|
| 1537 |
+
template_folder=template_dir,
|
| 1538 |
+
|
| 1539 |
+
model_repo_id=self.model_repo_id,
|
| 1540 |
+
|
| 1541 |
+
base_model_dict=self.hf_base_model_dict,
|
| 1542 |
+
training_dataset_dict=self.dataset_commit_dict,
|
| 1543 |
+
|
| 1544 |
+
version_label=new_model_version_label,
|
| 1545 |
+
commit_datetime=commit_datetime,
|
| 1546 |
+
perf_metrics=self.perf_metrics,
|
| 1547 |
+
|
| 1548 |
+
mf_flow_name=current.flow_name,
|
| 1549 |
+
mf_run_id=current.run.id
|
| 1550 |
+
)
|
| 1551 |
+
#############################
|
| 1552 |
+
|
| 1553 |
+
print("Pushing model version to HF hub " +
|
| 1554 |
+
("(blessed). " if self.model_version_blessed
|
| 1555 |
+
else "(not blessed). ") +
|
| 1556 |
+
"May take a while..",
|
| 1557 |
+
flush=True)
|
| 1558 |
+
model_commit_hash = push_model_version_to_hub(
|
| 1559 |
+
repo_id=self.model_repo_id,
|
| 1560 |
+
model_version_blessed=\
|
| 1561 |
+
self.model_version_blessed,
|
| 1562 |
+
version_label=new_model_version_label,
|
| 1563 |
+
timestamp_str=commit_datetime.strftime(
|
| 1564 |
+
"%Y-%m-%d %H:%M:%S UTC"),
|
| 1565 |
+
model_dir=self.sft_model_dir,
|
| 1566 |
+
model_readme_content=readme_content,
|
| 1567 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 1568 |
+
)
|
| 1569 |
+
if not model_commit_hash:
|
| 1570 |
+
raise Exception(
|
| 1571 |
+
"Failed to publish model version.")
|
| 1572 |
+
print("Push of model version to HF hub completed.",
|
| 1573 |
+
flush=True)
|
| 1574 |
+
print(f"https://huggingface.co/{self.model_repo_id}" +
|
| 1575 |
+
f"/blob/{model_commit_hash}/README.md")
|
| 1576 |
+
|
| 1577 |
+
self.model_commit_dict = {
|
| 1578 |
+
"repo_id": self.model_repo_id,
|
| 1579 |
+
"commit_hash": model_commit_hash,
|
| 1580 |
+
"version_label": new_model_version_label,
|
| 1581 |
+
"commit_datetime": commit_datetime,
|
| 1582 |
+
}
|
| 1583 |
+
|
| 1584 |
+
self.next(self.infra_validator)
|
| 1585 |
+
|
| 1586 |
+
|
| 1587 |
+
@step
|
| 1588 |
+
def infra_validator(self):
|
| 1589 |
+
"""
|
| 1590 |
+
If the trained model version is blessed,
|
| 1591 |
+
validate serving.
|
| 1592 |
+
"""
|
| 1593 |
+
"""
|
| 1594 |
+
Note that using isolated virtual env
|
| 1595 |
+
(using @conda task decorator)
|
| 1596 |
+
is advisable to not embark the whole
|
| 1597 |
+
pipeline dependencies into the local server.
|
| 1598 |
+
We don't for educational purpose,
|
| 1599 |
+
keep things "simple" to grasp
|
| 1600 |
+
as well as to avoid forcing conda
|
| 1601 |
+
(for instance miniconda) as
|
| 1602 |
+
a virtual environment management mean
|
| 1603 |
+
to the user.
|
| 1604 |
+
"""
|
| 1605 |
+
"""
|
| 1606 |
+
Note : We load base model from HF-cache
|
| 1607 |
+
(mounted as /huggingface_hub_cache
|
| 1608 |
+
docker volume) and adapter from local dir
|
| 1609 |
+
(mounted as /FuncCallAdater docker volume.
|
| 1610 |
+
"""
|
| 1611 |
+
|
| 1612 |
+
self.local_serve_is_ready = LocalServeReadinessEnum.NOT_APPLICABLE
|
| 1613 |
+
|
| 1614 |
+
if self.model_version_blessed:
|
| 1615 |
+
from retrain_pipelines.utils.docker import \
|
| 1616 |
+
env_has_docker
|
| 1617 |
+
|
| 1618 |
+
if env_has_docker():
|
| 1619 |
+
model_module_dir = \
|
| 1620 |
+
os.path.dirname(
|
| 1621 |
+
importlib.util.find_spec(
|
| 1622 |
+
"retrain_pipelines.model." +
|
| 1623 |
+
os.getenv('retrain_pipeline_type')
|
| 1624 |
+
).origin)
|
| 1625 |
+
|
| 1626 |
+
# server & data-model & server-config modules artifacts
|
| 1627 |
+
files_to_copy = [
|
| 1628 |
+
"litserve_server.py",
|
| 1629 |
+
"litserve_datamodel.py",
|
| 1630 |
+
"litserve_serverconfig.py",
|
| 1631 |
+
".dockerignore" # docker context loading
|
| 1632 |
+
# at image-build time,
|
| 1633 |
+
# exclude model weights
|
| 1634 |
+
]
|
| 1635 |
+
for filename in files_to_copy:
|
| 1636 |
+
shutil.copy(
|
| 1637 |
+
os.path.join(model_module_dir, "litserve",
|
| 1638 |
+
filename),
|
| 1639 |
+
os.path.join(self.serving_artifacts_local_folder,
|
| 1640 |
+
filename)
|
| 1641 |
+
)
|
| 1642 |
+
|
| 1643 |
+
# save dependencies as artifact
|
| 1644 |
+
create_requirements(self.serving_artifacts_local_folder,
|
| 1645 |
+
exclude=["cudf-polars-.*", "cuda-python",
|
| 1646 |
+
"nvidia-.*", "(py)?libcudf-.*",
|
| 1647 |
+
"nvtx", "rmm-.*", "litserve",
|
| 1648 |
+
".*retrain-pipelines.*"]
|
| 1649 |
+
)
|
| 1650 |
+
|
| 1651 |
+
# server config yaml
|
| 1652 |
+
env = Environment(loader=FileSystemLoader(
|
| 1653 |
+
os.path.join(model_module_dir, "litserve")))
|
| 1654 |
+
template = env.get_template(
|
| 1655 |
+
"litserve_serverconfig_template.yaml")
|
| 1656 |
+
server_config_data = {
|
| 1657 |
+
"port": "8000",
|
| 1658 |
+
"max_seq_length": self.max_seq_length,
|
| 1659 |
+
"max_new_token": self.max_new_tokens,
|
| 1660 |
+
"base_model": {
|
| 1661 |
+
"repo_id": self.hf_base_model_dict["repo_id"],
|
| 1662 |
+
"revision": self.hf_base_model_dict["commit_hash"]
|
| 1663 |
+
},
|
| 1664 |
+
"adapters": [
|
| 1665 |
+
{
|
| 1666 |
+
"name": "func_caller",
|
| 1667 |
+
"path": "/FuncCallAdapter"
|
| 1668 |
+
}
|
| 1669 |
+
]
|
| 1670 |
+
}
|
| 1671 |
+
server_config_yaml = template.render(server_config_data)
|
| 1672 |
+
print(server_config_yaml)
|
| 1673 |
+
with open(os.path.join(
|
| 1674 |
+
self.serving_artifacts_local_folder,
|
| 1675 |
+
"litserve_serverconfig.yaml"), 'w'
|
| 1676 |
+
) as output_file:
|
| 1677 |
+
output_file.write(server_config_yaml)
|
| 1678 |
+
|
| 1679 |
+
# Dockerfile
|
| 1680 |
+
env = Environment(loader=FileSystemLoader(
|
| 1681 |
+
os.path.join(model_module_dir)))
|
| 1682 |
+
template = env.get_template(
|
| 1683 |
+
"Dockerfile.litserve_template")
|
| 1684 |
+
# Change CUDA version here from available list
|
| 1685 |
+
# @see https://hub.docker.com/r/nvidia/cuda/tags
|
| 1686 |
+
dockerfile_content = template.render(
|
| 1687 |
+
{"cuda_version": "12.0.0"})
|
| 1688 |
+
with open(os.path.join(
|
| 1689 |
+
self.serving_artifacts_local_folder,
|
| 1690 |
+
"Dockerfile.litserve"), 'w'
|
| 1691 |
+
) as output_file:
|
| 1692 |
+
output_file.write(dockerfile_content)
|
| 1693 |
+
|
| 1694 |
+
os.environ["no_proxy"] = "localhost,127.0.0.1,0.0.0.0"
|
| 1695 |
+
|
| 1696 |
+
############################################
|
| 1697 |
+
# actually deploy the inference service #
|
| 1698 |
+
############################################
|
| 1699 |
+
start_time = time.time()
|
| 1700 |
+
from retrain_pipelines.utils.docker import \
|
| 1701 |
+
build_and_run_docker, print_container_log_tail, \
|
| 1702 |
+
cleanup_docker
|
| 1703 |
+
from retrain_pipelines.model.litserve import \
|
| 1704 |
+
endpoint_started, endpoint_is_ready
|
| 1705 |
+
|
| 1706 |
+
self.port = 8765
|
| 1707 |
+
HF_HUB_CACHE = os.path.realpath(os.path.expanduser(
|
| 1708 |
+
os.getenv(
|
| 1709 |
+
"HF_HUB_CACHE",
|
| 1710 |
+
os.path.join(os.getenv("HF_HOME",
|
| 1711 |
+
"~/.cache/huggingface"),
|
| 1712 |
+
"hub")
|
| 1713 |
+
)))
|
| 1714 |
+
print(f"HF_HUB_CACHE : {HF_HUB_CACHE}")
|
| 1715 |
+
image_name = container_name = "litserve-model"
|
| 1716 |
+
|
| 1717 |
+
serving_container = build_and_run_docker(
|
| 1718 |
+
image_name=image_name, image_tag="1.0",
|
| 1719 |
+
build_path=self.serving_artifacts_local_folder,
|
| 1720 |
+
dockerfile="Dockerfile.litserve",
|
| 1721 |
+
ports_publish_dict={'8000/tcp': self.port},
|
| 1722 |
+
env_vars_dict={
|
| 1723 |
+
"HF_HUB_CACHE": "/huggingface_hub_cache",
|
| 1724 |
+
"HF_TOKEN": os.getenv("HF_TOKEN")
|
| 1725 |
+
},
|
| 1726 |
+
volumes_dict={
|
| 1727 |
+
self.sft_model_dir:
|
| 1728 |
+
{"bind": "/FuncCallAdapter",
|
| 1729 |
+
"mode": "ro"},
|
| 1730 |
+
HF_HUB_CACHE:
|
| 1731 |
+
{"bind": "/huggingface_hub_cache",
|
| 1732 |
+
"mode": "ro"}
|
| 1733 |
+
}
|
| 1734 |
+
)
|
| 1735 |
+
|
| 1736 |
+
if not serving_container:
|
| 1737 |
+
print("failed spinning the LitServe container",
|
| 1738 |
+
file=sys.stderr)
|
| 1739 |
+
self.local_serve_is_ready = \
|
| 1740 |
+
LocalServeReadinessEnum.FAILURE
|
| 1741 |
+
try:
|
| 1742 |
+
cleanup_docker(
|
| 1743 |
+
container_name=container_name,
|
| 1744 |
+
image_name=f"{image_name}:1.0",
|
| 1745 |
+
no_pruning=True # for intermediate layers recycling
|
| 1746 |
+
# (during later re-runs)
|
| 1747 |
+
# to avoid long rebuild time
|
| 1748 |
+
# of exactly the same.
|
| 1749 |
+
)
|
| 1750 |
+
except Exception as cleanup_ex:
|
| 1751 |
+
# fail silently
|
| 1752 |
+
pass
|
| 1753 |
+
else:
|
| 1754 |
+
print("Awaiting endpoint launch..")
|
| 1755 |
+
start_time = time.time()
|
| 1756 |
+
if not endpoint_started(
|
| 1757 |
+
container_name, port=self.port, timeout=10*60
|
| 1758 |
+
):
|
| 1759 |
+
print(
|
| 1760 |
+
f"The endpoint '{container_name}' " +
|
| 1761 |
+
f"did not start.")
|
| 1762 |
+
self.local_serve_is_ready = \
|
| 1763 |
+
LocalServeReadinessEnum.FAILURE
|
| 1764 |
+
# health check on the spun-up endpoint
|
| 1765 |
+
elif endpoint_is_ready(port=self.port):
|
| 1766 |
+
self.local_serve_is_ready = \
|
| 1767 |
+
LocalServeReadinessEnum.SUCCESS
|
| 1768 |
+
elapsed_time = time.time() - start_time
|
| 1769 |
+
print("deploy_local - Elapsed time: " +
|
| 1770 |
+
f"{elapsed_time:.2f} seconds")
|
| 1771 |
+
############################################
|
| 1772 |
+
else:
|
| 1773 |
+
# env doesn't have docker
|
| 1774 |
+
self.local_serve_is_ready = \
|
| 1775 |
+
LocalServeReadinessEnum.FAILURE_NO_DOCKER
|
| 1776 |
+
|
| 1777 |
+
if LocalServeReadinessEnum.SUCCESS == self.local_serve_is_ready:
|
| 1778 |
+
from retrain_pipelines.model.litserve.litserve_datamodel \
|
| 1779 |
+
import Response
|
| 1780 |
+
|
| 1781 |
+
import requests
|
| 1782 |
+
|
| 1783 |
+
url = f"http://localhost:{self.port}/predict"
|
| 1784 |
+
headers = {"accept": "application/x-www-form-urlencoded"}
|
| 1785 |
+
|
| 1786 |
+
try:
|
| 1787 |
+
start_time = time.time()
|
| 1788 |
+
data = {
|
| 1789 |
+
"adapter_name": "func_caller",
|
| 1790 |
+
"queries": '["Hello.", "Is 49 a perfect square?"]'
|
| 1791 |
+
}
|
| 1792 |
+
print(f"inference test - data: {data}")
|
| 1793 |
+
response = requests.post(url, headers=headers, data=data)
|
| 1794 |
+
parsed_response = Response(**{"output": response.json()})
|
| 1795 |
+
elapsed_time = time.time() - start_time
|
| 1796 |
+
print("parsed_response ('func_caller' adapter ON) :" +
|
| 1797 |
+
str(parsed_response) +
|
| 1798 |
+
f"\t-\tElapsed time: {elapsed_time:.2f} seconds")
|
| 1799 |
+
|
| 1800 |
+
start_time = time.time()
|
| 1801 |
+
data = {
|
| 1802 |
+
"queries": '["Hello.", "Is 49 a perfect square?"]'
|
| 1803 |
+
}
|
| 1804 |
+
print(f"inference test - data: {data}")
|
| 1805 |
+
response = requests.post(url, headers=headers, data=data)
|
| 1806 |
+
parsed_response = Response(**{"output": response.json()})
|
| 1807 |
+
elapsed_time = time.time() - start_time
|
| 1808 |
+
print(f"parsed_response (no adapter) : {parsed_response}" +
|
| 1809 |
+
f"\t-\tElapsed time: {elapsed_time:.2f} seconds")
|
| 1810 |
+
|
| 1811 |
+
except Exception as ex:
|
| 1812 |
+
print(ex, file=sys.stderr)
|
| 1813 |
+
traceback.print_tb(ex.__traceback__, file=sys.stderr)
|
| 1814 |
+
self.local_serve_is_ready = \
|
| 1815 |
+
LocalServeReadinessEnum.FAILURE
|
| 1816 |
+
pass
|
| 1817 |
+
|
| 1818 |
+
try:
|
| 1819 |
+
cleanup_docker(
|
| 1820 |
+
container_name=container_name,
|
| 1821 |
+
image_name=f"{image_name}:1.0",
|
| 1822 |
+
no_pruning=True # for intermediate layers recycling
|
| 1823 |
+
# (during later re-runs)
|
| 1824 |
+
# to avoid long rebuild time
|
| 1825 |
+
# of exactly the same.
|
| 1826 |
+
)
|
| 1827 |
+
except Exception as cleanup_ex:
|
| 1828 |
+
# fail silently
|
| 1829 |
+
pass
|
| 1830 |
+
|
| 1831 |
+
self.next(self.pipeline_card)
|
| 1832 |
+
|
| 1833 |
+
|
| 1834 |
+
@card(id='default')
|
| 1835 |
+
@card(type='html', id='custom')
|
| 1836 |
+
@step
|
| 1837 |
+
def pipeline_card(self):
|
| 1838 |
+
import re
|
| 1839 |
+
import datetime
|
| 1840 |
+
import importlib.metadata
|
| 1841 |
+
|
| 1842 |
+
#############################
|
| 1843 |
+
# case of user-provided #
|
| 1844 |
+
# documentation artifact(s) #
|
| 1845 |
+
#############################
|
| 1846 |
+
# note that user can provide either
|
| 1847 |
+
# 'pipeline_card.py' or 'template.html'
|
| 1848 |
+
# or 'dataset_readme.py'
|
| 1849 |
+
# or 'dataset_readme_template.md'
|
| 1850 |
+
# or 'model_readme.py'
|
| 1851 |
+
# or 'model_readme_template.md'
|
| 1852 |
+
# or any combination of those
|
| 1853 |
+
# when specifying custom
|
| 1854 |
+
# 'pipeline_card_artifacts_path'
|
| 1855 |
+
if "template.html" in os.listdir(
|
| 1856 |
+
self.pipeline_card_artifacts_path
|
| 1857 |
+
):
|
| 1858 |
+
template_dir = self.pipeline_card_artifacts_path
|
| 1859 |
+
else:
|
| 1860 |
+
template_dir = os.path.dirname(
|
| 1861 |
+
importlib.util.find_spec(
|
| 1862 |
+
f"retrain_pipelines.pipeline_card."+
|
| 1863 |
+
f"{os.getenv('retrain_pipeline_type')}"
|
| 1864 |
+
).origin)
|
| 1865 |
+
#############################
|
| 1866 |
+
if "pipeline_card.py" in os.listdir(
|
| 1867 |
+
self.pipeline_card_artifacts_path
|
| 1868 |
+
):
|
| 1869 |
+
from retrain_pipelines.utils import get_get_html
|
| 1870 |
+
get_html = \
|
| 1871 |
+
get_get_html(self.pipeline_card_artifacts_path)
|
| 1872 |
+
else:
|
| 1873 |
+
from retrain_pipelines.pipeline_card import \
|
| 1874 |
+
get_html
|
| 1875 |
+
from retrain_pipelines.pipeline_card.helpers import \
|
| 1876 |
+
mf_dag_svg
|
| 1877 |
+
#############################
|
| 1878 |
+
|
| 1879 |
+
|
| 1880 |
+
#############################
|
| 1881 |
+
## "default" card ##
|
| 1882 |
+
#############################
|
| 1883 |
+
self.metadata = {
|
| 1884 |
+
"name": "TabNet Model",
|
| 1885 |
+
"version": "1.0",
|
| 1886 |
+
"retrain_pipelines": f"retrain-pipelines {__version__}",
|
| 1887 |
+
"retrain_pipeline_type": os.environ["retrain_pipeline_type"],
|
| 1888 |
+
"description": "A PyTorch TabNet model retrained",
|
| 1889 |
+
"authors": [current.username],
|
| 1890 |
+
"tags": ["classification", "tabnet"],
|
| 1891 |
+
"license": "MIT License",
|
| 1892 |
+
"data_augmentation": [
|
| 1893 |
+
{
|
| 1894 |
+
"name": "Augmentation",
|
| 1895 |
+
"description": "Truncating queries and " + \
|
| 1896 |
+
"associate those to " + \
|
| 1897 |
+
"no tool-call answers. " + \
|
| 1898 |
+
"Intent being to instruct on " + \
|
| 1899 |
+
"not hallucinating missing " + \
|
| 1900 |
+
"tool-calls parameters values."
|
| 1901 |
+
},
|
| 1902 |
+
{
|
| 1903 |
+
"name": "Enrichment",
|
| 1904 |
+
"description": "Addition of records " + \
|
| 1905 |
+
"from an external data-source. " + \
|
| 1906 |
+
"Here to instruct on no tool-call."
|
| 1907 |
+
}
|
| 1908 |
+
],
|
| 1909 |
+
"references": [
|
| 1910 |
+
{
|
| 1911 |
+
"title": "Base model",
|
| 1912 |
+
"link": f"https://hf.co/{self.hf_base_model_dict['repo_id']}"
|
| 1913 |
+
},
|
| 1914 |
+
{
|
| 1915 |
+
"title": "Function-calling dataset",
|
| 1916 |
+
"link": f"https://hf.co/{self.hf_dataset_dict['repo_id']}"
|
| 1917 |
+
},
|
| 1918 |
+
{
|
| 1919 |
+
"title": "Data-enrichment dataset",
|
| 1920 |
+
"link": f"https://hf.co/{self.hf_enrich_dataset_dict['repo_id']}"
|
| 1921 |
+
},
|
| 1922 |
+
{
|
| 1923 |
+
"title": "Unsloth",
|
| 1924 |
+
"link": "https://unsloth.ai/blog/contpretraining"
|
| 1925 |
+
}
|
| 1926 |
+
]
|
| 1927 |
+
}
|
| 1928 |
+
|
| 1929 |
+
current.card['default'].append(Markdown(
|
| 1930 |
+
"model_version_blessed : **%s**" % str(self.model_version_blessed)))
|
| 1931 |
+
current.card['default'].append(Artifact(
|
| 1932 |
+
{"model_version_blessed": self.model_version_blessed}))
|
| 1933 |
+
|
| 1934 |
+
current.card['default'].append(
|
| 1935 |
+
Image.from_matplotlib(self.sft_log_history_fig))
|
| 1936 |
+
current.card['default'].append(
|
| 1937 |
+
Image.from_matplotlib(self.validation_completions_fig))
|
| 1938 |
+
#############################
|
| 1939 |
+
|
| 1940 |
+
#############################
|
| 1941 |
+
## html "custom" card ##
|
| 1942 |
+
#############################
|
| 1943 |
+
dt = datetime.datetime.now(tz=datetime.timezone.utc)
|
| 1944 |
+
formatted_dt = dt.strftime("%A %b %d %Y %I:%M:%S %p %Z")
|
| 1945 |
+
task_obj_python_cmd = f"metaflow.Task(" + \
|
| 1946 |
+
f"\"{current.pathspec}\", " + \
|
| 1947 |
+
f"attempt={str(current.retry_count)})"
|
| 1948 |
+
params={
|
| 1949 |
+
'template_dir': template_dir,
|
| 1950 |
+
'title': f"{current.flow_name}",
|
| 1951 |
+
"subtitle": f"(flow run # {len(list(current.run.parent.runs()))}," + \
|
| 1952 |
+
f" run_id: {str(current.run.id)} - {formatted_dt})",
|
| 1953 |
+
'model_version_blessed': self.model_version_blessed,
|
| 1954 |
+
# 'current_blessed_run': self.current_blessed_run,
|
| 1955 |
+
'current_blessed_model_commit_hash': (
|
| 1956 |
+
self.current_blessed_version_dict["commit_hash"]
|
| 1957 |
+
if self.current_blessed_version_dict
|
| 1958 |
+
else None
|
| 1959 |
+
),
|
| 1960 |
+
'LocalServeReadinessEnum': LocalServeReadinessEnum,
|
| 1961 |
+
'local_serve_is_ready': self.local_serve_is_ready,
|
| 1962 |
+
# EDA
|
| 1963 |
+
'main_dataset_repo_id': self.hf_dataset['repo_id'],
|
| 1964 |
+
'main_dataset_commit_hash': self.hf_dataset_dict['commit_hash'],
|
| 1965 |
+
'main_dataset_commit_datetime': \
|
| 1966 |
+
self.hf_dataset_dict['commit_datetime'],
|
| 1967 |
+
|
| 1968 |
+
'records_count': self.records_count,
|
| 1969 |
+
'data_schema': self.data_schema,
|
| 1970 |
+
'answers_tools_count_fig': self.answers_tools_count_fig,
|
| 1971 |
+
'words_count_fig': self.words_count_fig,
|
| 1972 |
+
|
| 1973 |
+
# model training
|
| 1974 |
+
'dataset_repo_id': self.dataset_repo_id,
|
| 1975 |
+
'dataset_version_label': self.dataset_commit_dict["version_label"],
|
| 1976 |
+
'dataset_commit_datetime': self.dataset_commit_dict["commit_datetime"],
|
| 1977 |
+
'dataset_commit_hash': self.dataset_commit_dict["commit_hash"],
|
| 1978 |
+
'dataset_augmentation_rate': self.actual_augmentation_rate,
|
| 1979 |
+
'dataset_enrichment_rate': self.enrichment_rate,
|
| 1980 |
+
|
| 1981 |
+
'model_repo_id': self.model_repo_id,
|
| 1982 |
+
'model_version_label': self.model_commit_dict["version_label"],
|
| 1983 |
+
'model_commit_datetime': self.model_commit_dict["commit_datetime"],
|
| 1984 |
+
'model_commit_hash': self.model_commit_dict["commit_hash"],
|
| 1985 |
+
|
| 1986 |
+
'cpt_log_history_fig': self.cpt_log_history_fig,
|
| 1987 |
+
'sft_log_history_fig': self.sft_log_history_fig,
|
| 1988 |
+
|
| 1989 |
+
'validation_completions_fig': self.validation_completions_fig,
|
| 1990 |
+
|
| 1991 |
+
'pipeline_parameters_dict': {"cpt": self.cpt_training_args,
|
| 1992 |
+
"sft": self.sft_training_args},
|
| 1993 |
+
|
| 1994 |
+
'metrics_dict': self.perf_metrics,
|
| 1995 |
+
|
| 1996 |
+
'task_obj_python_cmd': task_obj_python_cmd,
|
| 1997 |
+
'dag_svg': mf_dag_svg(self)
|
| 1998 |
+
}
|
| 1999 |
+
self.html = get_html(params)
|
| 2000 |
+
#############################
|
| 2001 |
+
current
|
| 2002 |
+
#############################
|
| 2003 |
+
|
| 2004 |
+
self.next(self.pipeline_to_hub)
|
| 2005 |
+
|
| 2006 |
+
|
| 2007 |
+
@step
|
| 2008 |
+
def pipeline_to_hub(self):
|
| 2009 |
+
"""
|
| 2010 |
+
publish versioned source-code and pipeline-card
|
| 2011 |
+
for ths run on the Hugging Face Hub.
|
| 2012 |
+
"""
|
| 2013 |
+
|
| 2014 |
+
model_commit_datetime = \
|
| 2015 |
+
self.model_commit_dict["commit_datetime"]
|
| 2016 |
+
timestamp_str = \
|
| 2017 |
+
"{:%Y%m%d_%H%M%S}".format(model_commit_datetime) + \
|
| 2018 |
+
"{:03d}".format(model_commit_datetime.microsecond//1000) + \
|
| 2019 |
+
"_UTC"
|
| 2020 |
+
subfolder_name = \
|
| 2021 |
+
"v" + self.model_commit_dict["version_label"] + \
|
| 2022 |
+
"_" + timestamp_str
|
| 2023 |
+
commit_datetime = datetime.utcnow()
|
| 2024 |
+
|
| 2025 |
+
###############################
|
| 2026 |
+
# source-code #
|
| 2027 |
+
###############################
|
| 2028 |
+
# We upload only herein file #
|
| 2029 |
+
# plus user-provided versions #
|
| 2030 |
+
# of the customizable ones #
|
| 2031 |
+
# (if any). #
|
| 2032 |
+
###############################
|
| 2033 |
+
custom_source_files = [os.path.abspath(__file__)]
|
| 2034 |
+
if (
|
| 2035 |
+
self.pipeline_card_artifacts_path != \
|
| 2036 |
+
self.default_pipeline_card_module_dir
|
| 2037 |
+
):
|
| 2038 |
+
candidate_source_files = [
|
| 2039 |
+
"pipeline_card.py",
|
| 2040 |
+
"template.html",
|
| 2041 |
+
"dataset_readme.py",
|
| 2042 |
+
"dataset_readme_template.md",
|
| 2043 |
+
"model_readme.py",
|
| 2044 |
+
"model_readme_template.md"
|
| 2045 |
+
]
|
| 2046 |
+
for candidate_source_file in candidate_source_files:
|
| 2047 |
+
file_fullpath = os.path.join(
|
| 2048 |
+
self.pipeline_card_artifacts_path,
|
| 2049 |
+
candidate_source_file)
|
| 2050 |
+
if os.path.exists(file_fullpath):
|
| 2051 |
+
custom_source_files.append(file_fullpath)
|
| 2052 |
+
|
| 2053 |
+
source_code_commit_hash = \
|
| 2054 |
+
push_files_to_hub_repo_branch(
|
| 2055 |
+
repo_id=self.model_repo_id,
|
| 2056 |
+
branch_name="retrain-pipelines_source-code",
|
| 2057 |
+
file_fullnames=custom_source_files,
|
| 2058 |
+
include_requirements_txt=True,
|
| 2059 |
+
path_in_repo=subfolder_name,
|
| 2060 |
+
commit_message=\
|
| 2061 |
+
"source-code for model version " + \
|
| 2062 |
+
subfolder_name + \
|
| 2063 |
+
f"- retrain-pipelines {__version__}",
|
| 2064 |
+
repo_type="model",
|
| 2065 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 2066 |
+
)
|
| 2067 |
+
print(source_code_commit_hash)
|
| 2068 |
+
self.source_code_commit_dict = {
|
| 2069 |
+
"repo_id": self.model_repo_id,
|
| 2070 |
+
"branch_name": "retrain-pipelines_source-code",
|
| 2071 |
+
"commit_datetime": commit_datetime,
|
| 2072 |
+
"commit_hash": source_code_commit_hash
|
| 2073 |
+
}
|
| 2074 |
+
###############################
|
| 2075 |
+
|
| 2076 |
+
###############################
|
| 2077 |
+
# pipeline-card #
|
| 2078 |
+
###############################
|
| 2079 |
+
pipeline_card_fullname = None
|
| 2080 |
+
for run_step in current.run.steps():
|
| 2081 |
+
task = list(run_step.tasks())[0]
|
| 2082 |
+
task_name = task.path_components[2]
|
| 2083 |
+
if "pipeline_card" == task_name:
|
| 2084 |
+
pipeline_card = get_cards(
|
| 2085 |
+
task, id='custom', type='html')[0]
|
| 2086 |
+
pipeline_card_fullname = os.path.realpath(
|
| 2087 |
+
os.path.join(
|
| 2088 |
+
task.metadata_dict.get("ds-root", None),
|
| 2089 |
+
mf_config.CARD_SUFFIX, pipeline_card.path
|
| 2090 |
+
))
|
| 2091 |
+
print(pipeline_card_fullname)
|
| 2092 |
+
break
|
| 2093 |
+
pipeline_card_commit_hash = \
|
| 2094 |
+
push_files_to_hub_repo_branch(
|
| 2095 |
+
repo_id=self.model_repo_id,
|
| 2096 |
+
branch_name="retrain-pipelines_pipeline-card",
|
| 2097 |
+
file_fullnames=[pipeline_card_fullname],
|
| 2098 |
+
path_in_repo=subfolder_name,
|
| 2099 |
+
commit_message=\
|
| 2100 |
+
"pipeline-card for model version " + \
|
| 2101 |
+
subfolder_name + \
|
| 2102 |
+
f"- retrain-pipelines {__version__}",
|
| 2103 |
+
repo_type="model",
|
| 2104 |
+
hf_token=os.getenv("HF_TOKEN", None)
|
| 2105 |
+
)
|
| 2106 |
+
print(pipeline_card_commit_hash)
|
| 2107 |
+
self.pipeline_card_commit_dict = {
|
| 2108 |
+
"repo_id": self.model_repo_id,
|
| 2109 |
+
"branch_name": "retrain-pipelines_pipeline-card",
|
| 2110 |
+
"commit_datetime": commit_datetime,
|
| 2111 |
+
"commit_hash": pipeline_card_commit_hash
|
| 2112 |
+
}
|
| 2113 |
+
###############################
|
| 2114 |
+
|
| 2115 |
+
self.next(self.deploy)
|
| 2116 |
+
|
| 2117 |
+
|
| 2118 |
+
@step
|
| 2119 |
+
def deploy(self):
|
| 2120 |
+
"""
|
| 2121 |
+
placeholder for the serving SDK deploy call
|
| 2122 |
+
(on the target production platform).
|
| 2123 |
+
Include any artifact you want,
|
| 2124 |
+
consider including the portable pipelione-card
|
| 2125 |
+
itself !
|
| 2126 |
+
"""
|
| 2127 |
+
|
| 2128 |
+
if (
|
| 2129 |
+
self.model_version_blessed and
|
| 2130 |
+
(self.local_serve_is_ready == LocalServeReadinessEnum.SUCCESS)
|
| 2131 |
+
):
|
| 2132 |
+
pass # your code here
|
| 2133 |
+
|
| 2134 |
+
self.next(self.load_test)
|
| 2135 |
+
|
| 2136 |
+
|
| 2137 |
+
@step
|
| 2138 |
+
def load_test(self):
|
| 2139 |
+
"""
|
| 2140 |
+
placeholder
|
| 2141 |
+
"""
|
| 2142 |
+
|
| 2143 |
+
if (
|
| 2144 |
+
self.model_version_blessed and
|
| 2145 |
+
(self.local_serve_is_ready == LocalServeReadinessEnum.SUCCESS)
|
| 2146 |
+
):
|
| 2147 |
+
pass # your code here
|
| 2148 |
+
|
| 2149 |
+
self.next(self.end)
|
| 2150 |
+
|
| 2151 |
+
|
| 2152 |
+
@step
|
| 2153 |
+
def end(self):
|
| 2154 |
+
pass
|
| 2155 |
+
|
| 2156 |
+
|
| 2157 |
+
if __name__ == "__main__":
|
| 2158 |
+
UnslothFuncCallFlow()
|
| 2159 |
+
|