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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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4d12e619",
   "metadata": {},
   "source": [
    "# Geneformer Multi-Task Cell Classifier Tutorial\n",
    "\n",
    "This tutorial demonstrates how to use the Geneformer Multi-Task Cell Classifier and optimizatize hyperparameter for fine-tuning"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ae1e435",
   "metadata": {},
   "source": [
    "## 1. Installation and Imports\n",
    "\n",
    "First import the necessary modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8ae513f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from geneformer import MTLClassifier\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f2a696f",
   "metadata": {},
   "source": [
    "## 2. Set up Paths and Parameters\n",
    "\n",
    "Now, let's set up the necessary paths and parameters for our classifier. We'll also define our task columns, which are specific columns from our dataset that represent the classification tasks we want to train the model on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b86539a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define paths\n",
    "pretrained_path = \"/path/to/pretrained/Geneformer/model\" \n",
    "# input data is tokenized rank value encodings generated by Geneformer tokenizer (see tokenizing_scRNAseq_data.ipynb)\n",
    "train_path = \"/path/to/train/data.dataset\"\n",
    "val_path = \"/path/to/val/data.dataset\"\n",
    "test_path = \"/path/to/test/data.dataset\"\n",
    "results_dir = \"/path/to/results/directory\"\n",
    "model_save_path = \"/path/to/model/save/path\"\n",
    "tensorboard_log_dir = \"/path/to/tensorboard/log/dir\"\n",
    "\n",
    "# Define tasks and hyperparameters\n",
    "# task_columns should be a list of column names from your dataset\n",
    "# Each column represents a specific classification task (e.g. cell type, disease state)\n",
    "task_columns = [\"cell_type\", \"disease_state\"]  # Example task columns\n",
    "\n",
    "hyperparameters = {\n",
    "    \"learning_rate\": {\"type\": \"float\", \"low\": 1e-5, \"high\": 1e-3, \"log\": True},\n",
    "    \"warmup_ratio\": {\"type\": \"float\", \"low\": 0.005, \"high\": 0.01},\n",
    "    \"weight_decay\": {\"type\": \"float\", \"low\": 0.01, \"high\": 0.1},\n",
    "    \"dropout_rate\": {\"type\": \"float\", \"low\": 0.0, \"high\": 0.7},\n",
    "    \"lr_scheduler_type\": {\"type\": \"categorical\", \"choices\": [\"cosine\"]},\n",
    "    \"task_weights\": {\"type\": \"float\", \"low\": 0.1, \"high\": 2.0}\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6f6b315",
   "metadata": {},
   "source": [
    "In the code above, we've defined `task_columns` as `[\"cell_type\", \"disease_state\"]`. This means our model will be trained to classify cells based on two tasks:\n",
    "1. Identifying the cell type\n",
    "2. Determining the disease state\n",
    "3. Note: \"unique_cell_id\" is a required column in the dataset for logging and inference purposes\n",
    "\n",
    "These column names should correspond to actual columns in your dataset. Each column should contain the labels for that specific classification task.\n",
    "\n",
    "For example, your dataset might look something like this:\n",
    "\n",
    "    | unique_cell_id | input_ids | ... | cell_type | disease_state |\n",
    "    |----------------|-----------|-----|-----------|---------------|\n",
    "    | cell1          | ...       | ... | neuron    | healthy       |\n",
    "    | cell2          | ...       | ... | astrocyte | diseased      |\n",
    "    | ...            | ...       | ... | ...       | ...           |\n",
    "The model will learn to predict classes within 'cell_type' and 'disease_state' "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60883719",
   "metadata": {},
   "source": [
    "## 3. Initialize the MTLClassifier\n",
    "\n",
    "Now, let's create an instance of the MTLClassifier with our defined parameters and task columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "26a8e9ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "mc = MTLClassifier(\n",
    "    task_columns=task_columns,  # Our defined classification tasks\n",
    "    study_name=\"MTLClassifier_example\",\n",
    "    pretrained_path=pretrained_path,\n",
    "    train_path=train_path,\n",
    "    val_path=val_path,\n",
    "    test_path=test_path,\n",
    "    model_save_path=model_save_path,\n",
    "    results_dir=results_dir,\n",
    "    tensorboard_log_dir=tensorboard_log_dir,\n",
    "    hyperparameters=hyperparameters,\n",
    "    n_trials=15,  # Number of trials for hyperparameter optimization (at least 50 suggested)\n",
    "    epochs=1,    # Number of training epochs (1 suggested to prevent overfitting)\n",
    "    batch_size=8, # Adjust based on available GPU memory\n",
    "    seed=42\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a818abf1",
   "metadata": {},
   "source": [
    "## 4. Run Hyperparameter Optimization\n",
    "\n",
    "Now, let's run the Optuna study to optimize our hyperparameters for both classification tasks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8d8f3f35",
   "metadata": {},
   "outputs": [],
   "source": [
    "mc.run_optuna_study()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b7a82bf",
   "metadata": {},
   "source": [
    "## 5. Evaluate the Model on Test Data\n",
    "\n",
    "After optimization, we can evaluate our model on the test dataset. This will provide performance metrics for both classification tasks. CSV containing following keys will be generated in specified results directiory \"Cell ID, task(1...n) True,task(1.,.n) Pred,task(1...n) Probabilities\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0850e9f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "mc.load_and_evaluate_test_model()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35faa5a3",
   "metadata": {},
   "source": [
    "## 6. (Optional) Manual Hyperparameter Tuning\n",
    "\n",
    "If you prefer to set hyperparameters manually, you can use the following approach:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "26dd2a82",
   "metadata": {},
   "outputs": [],
   "source": [
    "manual_hyperparameters = {\n",
    "    \"learning_rate\": 0.001,\n",
    "    \"warmup_ratio\": 0.01,\n",
    "    \"weight_decay\": 0.1,\n",
    "    \"dropout_rate\": 0.1,\n",
    "    \"lr_scheduler_type\": \"cosine\",\n",
    "    \"task_weights\": [1, 1],  # Weights for each task (cell_type, disease_state)\n",
    "    \"max_layers_to_freeze\": 2\n",
    "}\n",
    "\n",
    "mc_manual = MTLClassifier(\n",
    "    task_columns=task_columns,\n",
    "    study_name=\"mtl_manual\",\n",
    "    pretrained_path=pretrained_path,\n",
    "    train_path=train_path,\n",
    "    val_path=val_path,\n",
    "    test_path=test_path,\n",
    "    model_save_path=model_save_path,\n",
    "    results_dir=results_dir,\n",
    "    tensorboard_log_dir=tensorboard_log_dir,\n",
    "    manual_hyperparameters=manual_hyperparameters,\n",
    "    use_manual_hyperparameters=True,\n",
    "    epochs=10,\n",
    "    batch_size=32,\n",
    "    seed=42\n",
    ")\n",
    "\n",
    "mc_manual.run_manual_tuning()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74c0a48b",
   "metadata": {},
   "source": [
    "# Geneformer In Silico Perturber Tutorial (MTL Quantized)\n",
    "This demonstrates how to use the Geneformer In Silico Perturber with a Multi-Task Learning (MTL) model in a quantized configuration to optimize runtime and memory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f262d53c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from geneformer import InSilicoPerturber, EmbExtractor, InSilicoPerturberStats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3636f2ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define paths\n",
    "model_directory = \"/path/to/model/save/path\"\n",
    "input_data_file = \"/path/to/input/data.dataset\"\n",
    "output_directory = \"/path/to/output/directory\"\n",
    "output_prefix = \"mtl_quantized_perturbation\"\n",
    "\n",
    "# Define parameters\n",
    "perturb_type = \"delete\"  # or \"overexpress\"\n",
    "\n",
    "# Define cell states to model\n",
    "cell_states_to_model = {\n",
    "    \"state_key\": \"disease_state\", \n",
    "    \"start_state\": \"disease\", \n",
    "    \"goal_state\": \"control\"\n",
    "}\n",
    "\n",
    "# Define filter data\n",
    "filter_data_dict = {\n",
    "    \"cell_type\": [\"Fibroblast\"]\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d15b7b51",
   "metadata": {},
   "source": [
    "## 3. Extract State Embeddings\n",
    "\n",
    "Before we initialize the InSilicoPerturber, we need to extract the state embeddings using the EmbExtractor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6b35bb30",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize EmbExtractor\n",
    "embex = EmbExtractor(\n",
    "    filter_data_dict=filter_data_dict,\n",
    "    max_ncells=1000, # Number of cells to extract embeddings for\n",
    "    emb_layer=0,  # Use the second to last layer\n",
    "    emb_mode = \"cls\",\n",
    "    summary_stat=\"exact_mean\",\n",
    "    forward_batch_size=8, # Adjust based on available GPU memory\n",
    "    nproc=4\n",
    ")\n",
    "\n",
    "# Extract state embeddings\n",
    "state_embs_dict = embex.get_state_embs(\n",
    "    cell_states_to_model,\n",
    "    model_directory=model_directory,\n",
    "    input_data_file=input_data_file,\n",
    "    output_directory=output_directory,\n",
    "    output_prefix=output_prefix\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6db01ced",
   "metadata": {},
   "source": [
    "## 4. Initialize the InSilicoPerturber\n",
    "\n",
    "Now that we have our state embeddings, let's create an instance of the InSilicoPerturber with MTL and quantized configurations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9bbecce2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize InSilicoPerturber\n",
    "isp = InSilicoPerturber(\n",
    "    perturb_type=perturb_type,\n",
    "    genes_to_perturb=\"all\",  # Perturb all genes\n",
    "    model_type=\"MTLCellClassifier-Quantized\",  # Use quantized MTL model\n",
    "    emb_mode=\"cls\",  # Use CLS token embedding\n",
    "    cell_states_to_model=cell_states_to_model,\n",
    "    state_embs_dict=state_embs_dict,\n",
    "    max_ncells=1000,  # Number of cells to perturb (larger number increases power)\n",
    "    emb_layer=0,  \n",
    "    forward_batch_size=8, # Adjust based on available GPU memory\n",
    "    nproc=1\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e447f8b0",
   "metadata": {},
   "source": [
    "## 5. Run In Silico Perturbation\n",
    "\n",
    "Run the in silico perturbation on the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4cc93922",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run perturbation and output intermediate files\n",
    "isp.perturb_data(\n",
    "    model_directory=model_directory,\n",
    "    input_data_file=input_data_file,\n",
    "    output_directory=output_directory,\n",
    "    output_prefix=output_prefix\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ec0b87e",
   "metadata": {},
   "source": [
    "## 6. Process Results with InSilicoPerturberStats\n",
    "\n",
    "After running the perturbation, we'll use InSilicoPerturberStats to process the intermediate files and generate the final statistics."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c8627d5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize InSilicoPerturberStats\n",
    "ispstats = InSilicoPerturberStats(\n",
    "    mode=\"goal_state_shift\",\n",
    "    genes_perturbed=\"all\",\n",
    "    combos=0,\n",
    "    anchor_gene=None,\n",
    "    cell_states_to_model=cell_states_to_model\n",
    ")\n",
    "\n",
    "# Process stats and output final .csv\n",
    "ispstats.get_stats(\n",
    "    input_data_file,\n",
    "    None,\n",
    "    output_directory,\n",
    "    output_prefix\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}