-
Notifications
You must be signed in to change notification settings - Fork 0
/
training_pipeline.yaml
194 lines (190 loc) · 11.1 KB
/
training_pipeline.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# PIPELINE DEFINITION
# Name: training-pipeline
# Inputs:
# bucket: str
# dataset_file: str
# gproject: str
# output_model_name: str
# Outputs:
# Output: str
components:
comp-start-distributed-training:
executorLabel: exec-start-distributed-training
inputDefinitions:
parameters:
bucket:
parameterType: STRING
dataset_file:
parameterType: STRING
gproject:
parameterType: STRING
output_model_name:
parameterType: STRING
outputDefinitions:
parameters:
Output:
parameterType: STRING
deploymentSpec:
executors:
exec-start-distributed-training:
container:
args:
- --executor_input
- '{{$}}'
- --function_to_execute
- start_distributed_training
command:
- sh
- -c
- "\nif ! [ -x \"$(command -v pip)\" ]; then\n python3 -m ensurepip ||\
\ python3 -m ensurepip --user || apt-get install python3-pip\nfi\n\nPIP_DISABLE_PIP_VERSION_CHECK=1\
\ python3 -m pip install --quiet --no-warn-script-location 'kfp==2.9.0'\
\ '--no-deps' 'typing-extensions>=3.7.4,<5; python_version<\"3.9\"' &&\
\ python3 -m pip install --quiet --no-warn-script-location 'gcsfs' 'transformers'\
\ 'datasets==2.16' 'evaluate==0.4.3' 'accelerate' 'scikit-learn' 'kubeflow-training'\
\ && \"$0\" \"$@\"\n"
- sh
- -ec
- 'program_path=$(mktemp -d)
printf "%s" "$0" > "$program_path/ephemeral_component.py"
_KFP_RUNTIME=true python3 -m kfp.dsl.executor_main --component_module_path "$program_path/ephemeral_component.py" "$@"
'
- "\nimport kfp\nfrom kfp import dsl\nfrom kfp.dsl import *\nfrom typing import\
\ *\n\ndef start_distributed_training(bucket: str, dataset_file: str, output_model_name:\
\ str, gproject: str) -> str:\n import os\n import gcsfs\n import\
\ numpy as np\n from datasets import load_dataset\n from datasets.distributed\
\ import split_dataset_by_node\n from transformers import (\n \
\ AutoModelForSequenceClassification,\n AutoTokenizer,\n Trainer,\n\
\ TrainingArguments,\n )\n from kubeflow.training import TrainingClient\n\
\ import torch\n\n def train_func(parameters):\n import os\n\
\ import gcsfs\n import numpy as np\n from datasets\
\ import load_dataset\n from datasets.distributed import split_dataset_by_node\n\
\ from transformers import (\n AutoModelForSequenceClassification,\n\
\ AutoTokenizer,\n Trainer,\n TrainingArguments,\n\
\ )\n from kubeflow.training import TrainingClient\n \
\ import torch\n import evaluate\n\n # load the dataset\
\ from gcs, not sure if best practice like this but it might work maybe\
\ automatically??\n # https://cloud.google.com/docs/authentication/application-default-credentials\n\
\ # TODO pass via parameters\n model_name = parameters['MODEL_NAME']\n\
\ storage_options= parameters['STORAGE_OPTIONS'] \n dataset\
\ = load_dataset(\"json\", data_files=f'gs://{parameters[\"BUCKET\"]}/{parameters[\"\
DATASET_FILE\"]}', storage_options=storage_options)\n ds = dataset[\"\
train\"].train_test_split(test_size=0.2)\n\n labels = [label for\
\ label in ds['train'].features.keys() if label not in ['body', 'title']]\n\
\ id2label = {idx:label for idx, label in enumerate(labels)}\n \
\ label2id = {label:idx for idx, label in enumerate(labels)}\n\n\n\
\ print(\"-\" * 40)\n print(\"Download BERT Model\")\n \
\ model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\"\
, \n problem_type=\"\
multi_label_classification\", \n \
\ num_labels=len(labels),\n \
\ id2label=id2label,\n \
\ label2id=label2id)\n\
\ tokenizer = AutoTokenizer.from_pretrained(\"bert-base-cased\")\n\
\n # [2] Preprocess dataset. \n def preprocess_data(example):\n\
\ text = f'{example[\"title\"]}\\n{example[\"body\"]}'\n \
\ # encode them\n encoding = tokenizer(text, padding=True, truncation=True)\n\
\n lbls = [0. for i in range(len(labels))]\n for label\
\ in labels:\n if label in example and example[label] == True:\n\
\ label_id = label2id[label]\n lbls[label_id]\
\ = 1.\n\n encoding[\"labels\"] = lbls \n return encoding\n\
\n # Map Yelp review dataset to BERT tokenizer.\n print(\"\
-\" * 40)\n print(\"Map dataset to BERT Tokenizer\")\n encoded_dataset\
\ = ds.map(preprocess_data, remove_columns=ds['train'].column_names)\n\n\
\ encoded_dataset.set_format(\"torch\") # ??\n\n # Distribute\
\ train and test datasets between PyTorch workers.\n # Every worker\
\ will process chunk of training data.\n # RANK and WORLD_SIZE will\
\ be set by Kubeflow Training Operator.\n RANK = int(os.environ[\"\
RANK\"])\n WORLD_SIZE = int(os.environ[\"WORLD_SIZE\"])\n \
\ distributed_ds_train = split_dataset_by_node(\n encoded_dataset[\"\
train\"],\n rank=RANK,\n world_size=WORLD_SIZE,\n\
\ )\n distributed_ds_test = split_dataset_by_node(\n \
\ encoded_dataset[\"test\"],\n rank=RANK,\n \
\ world_size=WORLD_SIZE,\n )\n\n # Evaluate accuracy. \n\
\ clf_metrics = evaluate.combine([\"accuracy\", \"f1\", \"precision\"\
, \"recall\"])\n\n def sigmoid(x):\n return 1/(1 + np.exp(-x))\n\
\n def compute_metrics(eval_pred):\n predictions, labels\
\ = eval_pred\n predictions = sigmoid(predictions)\n \
\ predictions = (predictions > 0.5).astype(int).reshape(-1)\n \
\ return clf_metrics.compute(predictions=predictions, references=labels.astype(int).reshape(-1))\n\
\n\n batch_size = 3\n metric_name = \"f1\"\n args =\
\ TrainingArguments(\n f\"{model_name}\",\n evaluation_strategy\
\ = \"epoch\",\n save_strategy = \"epoch\",\n learning_rate=2e-5,\n\
\ per_device_train_batch_size=batch_size,\n per_device_eval_batch_size=batch_size,\n\
\ num_train_epochs=5,\n weight_decay=0.01,\n \
\ load_best_model_at_end=True,\n metric_for_best_model=metric_name,\n\
\ #push_to_hub=True,\n )\n\n # [4] Define Trainer.\n\
\ trainer = Trainer(\n model=model,\n args=args,\n\
\ train_dataset=distributed_ds_train,\n eval_dataset=distributed_ds_test,\n\
\ tokenizer=tokenizer,\n compute_metrics=compute_metrics,\n\
\ )\n\n # [5] Fine-tune model.\n print(\"-\" * 40)\n\
\ print(f\"Start Distributed Training. RANK: {RANK} WORLD_SIZE: {WORLD_SIZE}\"\
)\n\n trainer.train()\n\n print(\"-\" * 40)\n print(\"\
Training is complete\")\n\n # [6] Export trained model to GCS from\
\ the worker with RANK = 0.\n if RANK == 0:\n trainer.save_model(f\"\
./{model_name}\")\n fs = gcsfs.GCSFileSystem(**storage_options)\n\
\ files = ['config.json', 'model.safetensors', 'special_tokens_map.json',\
\ 'tokenizer_config.json', 'tokenizer.json', 'training_args.bin', 'vocab.txt']\n\
\ for f in files: \n fs.put(f'{model_name}/{f}',\
\ f'{parameters[\"BUCKET\"]}/{model_name}/{f}')\n\n print(\"-\" *\
\ 40)\n print(\"Model export complete\")\n\n job_name = \"training-pipeline-job\"\
\n # Create PyTorchJob\n TrainingClient().create_job(\n name=job_name,\n\
\ train_func=train_func,\n parameters={\n \"BUCKET\"\
: bucket,\n \"STORAGE_OPTIONS\": {\"project\": gproject, \"token\"\
: \"google_default\"},\n \"MODEL_NAME\": output_model_name,\n\
\ \"DATASET_FILE\": dataset_file\n },\n num_workers=2,\
\ # Number of PyTorch workers to use.\n resources_per_worker={\n\
\ \"cpu\": \"3\",\n \"memory\": \"10G\",\n \
\ \"gpu\": \"1\",\n },\n packages_to_install=[\n \
\ \"gcsfs\",\n \"transformers\",\n \"datasets==2.16\"\
,\n \"evaluate\",\n \"accelerate\",\n \"\
scikit-learn\",\n \"kubeflow-training\"\n ], # PIP packages\
\ will be installed during PyTorchJob runtime.\n )\n # Wait until\
\ PyTorchJob has Running condition.\n job = TrainingClient().wait_for_job_conditions(\n\
\ job_name,\n expected_conditions={\"Running\"},\n )\n\
\ return \"job is running\"\n\n"
image: python:3.8
pipelineInfo:
name: training-pipeline
root:
dag:
outputs:
parameters:
Output:
valueFromParameter:
outputParameterKey: Output
producerSubtask: start-distributed-training
tasks:
start-distributed-training:
cachingOptions:
enableCache: true
componentRef:
name: comp-start-distributed-training
inputs:
parameters:
bucket:
componentInputParameter: bucket
dataset_file:
componentInputParameter: dataset_file
gproject:
componentInputParameter: gproject
output_model_name:
componentInputParameter: output_model_name
taskInfo:
name: start-distributed-training
inputDefinitions:
parameters:
bucket:
parameterType: STRING
dataset_file:
parameterType: STRING
gproject:
parameterType: STRING
output_model_name:
parameterType: STRING
outputDefinitions:
parameters:
Output:
parameterType: STRING
schemaVersion: 2.1.0
sdkVersion: kfp-2.9.0