{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# A Simple TF 2.1 notebook\n\nThis is based entirely off of Martin Gorner's excellent starter notebook, and is intended solely as a simple, shorter introduction to the operations being performed there.","metadata":{"_uuid":"a1c0e91b-82e0-4038-b999-f69d51230b34","_cell_guid":"0ab7baae-f97d-4871-af10-b7c550a5b0b7","trusted":true}},{"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"c68fda87-0dad-447f-9f6a-ed6fa365b64e","_cell_guid":"ac894bd1-2ecc-49c2-9164-957bcc3b27bb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:46:00.832579Z","iopub.execute_input":"2023-03-07T16:46:00.832909Z","iopub.status.idle":"2023-03-07T16:46:09.676556Z","shell.execute_reply.started":"2023-03-07T16:46:00.832876Z","shell.execute_reply":"2023-03-07T16:46:09.675562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Detect my accelerator","metadata":{"_uuid":"3b5d615a-3182-4f81-a8f3-cb6e54264e63","_cell_guid":"93dde2ac-0d09-4d46-a121-f2ecae88c786","trusted":true}},{"cell_type":"code","source":"# CHANGED FOR TPU 1VM:\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect(tpu=\"local\") # \"local\" for 1VM TPU\n    strategy = tf.distribute.TPUStrategy(tpu)\n    print(\"on TPU\")\nexcept tf.errors.NotFoundError:\n    print(\"not on TPU\")\n    strategy = tf.distribute.MirroredStrategy()\n    \nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"_uuid":"ca83590c-b66b-4a3f-a66c-672f851f6361","_cell_guid":"8cb47b9d-d19a-4a3d-89c4-49010783d95b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:46:09.677821Z","iopub.execute_input":"2023-03-07T16:46:09.678446Z","iopub.status.idle":"2023-03-07T16:46:19.797597Z","shell.execute_reply.started":"2023-03-07T16:46:09.678412Z","shell.execute_reply":"2023-03-07T16:46:19.796673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get my data path","metadata":{"_uuid":"0ac5b0f1-82b4-4f11-9a6a-20c5e9e0c217","_cell_guid":"2eef11e3-52b1-48c6-aced-1b23877d2542","trusted":true}},{"cell_type":"code","source":"# CHANGED FOR TPU 1VM: Direct access to the filesystem, no longer need to get_gcs_path()!\n#GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nGCS_DS_PATH = '/kaggle/input/flower-classification-with-tpus'","metadata":{"_uuid":"1cd5541c-e170-43a3-b2dd-edfbc5e9c1b0","_cell_guid":"501e1373-26a2-4f6c-a106-438be52d9a21","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:46:19.799731Z","iopub.execute_input":"2023-03-07T16:46:19.800181Z","iopub.status.idle":"2023-03-07T16:46:19.804324Z","shell.execute_reply.started":"2023-03-07T16:46:19.800148Z","shell.execute_reply":"2023-03-07T16:46:19.803399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set some parameters","metadata":{"_uuid":"242649f3-dd3c-48d3-8be1-e2cb9bc70583","_cell_guid":"e80238ac-95c4-471c-86b7-bd07d6a6db7e","trusted":true}},{"cell_type":"code","source":"IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 5\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"_uuid":"fd506828-093f-4291-b8e4-bb3512509cf7","_cell_guid":"fff4b014-6d83-4909-a9fd-396584ac486b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:46:19.805416Z","iopub.execute_input":"2023-03-07T16:46:19.805728Z","iopub.status.idle":"2023-03-07T16:46:19.816690Z","shell.execute_reply.started":"2023-03-07T16:46:19.805690Z","shell.execute_reply":"2023-03-07T16:46:19.815803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{"_uuid":"0eaf2aba-6dff-4726-933d-f5c3a40d2b44","_cell_guid":"5b03ba57-3f00-404f-939a-cd401bd2c350","trusted":true}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"_uuid":"b8a52a0f-50a0-4dab-a702-955a35600a17","_cell_guid":"71de7242-f9d9-4c29-8dfd-0ae79b8641c7","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:46:19.817791Z","iopub.execute_input":"2023-03-07T16:46:19.818121Z","iopub.status.idle":"2023-03-07T16:46:20.039265Z","shell.execute_reply.started":"2023-03-07T16:46:19.818094Z","shell.execute_reply":"2023-03-07T16:46:20.038464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!","metadata":{"_uuid":"d679cfbe-ba20-4c5d-a1a6-b0650058bc75","_cell_guid":"f0938c02-03e8-4603-9b17-38ef39ac3330","trusted":true}},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          validation_data=validation_dataset)","metadata":{"_uuid":"43c90f57-a8fb-4844-ae42-954e291d10aa","_cell_guid":"4423286c-bbc9-46e5-a20e-49600014692c","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:46:20.040338Z","iopub.execute_input":"2023-03-07T16:46:20.040602Z","iopub.status.idle":"2023-03-07T16:47:09.580291Z","shell.execute_reply.started":"2023-03-07T16:46:20.040578Z","shell.execute_reply":"2023-03-07T16:47:09.578850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{"_uuid":"6e881ca4-4aed-4f90-8b32-99991d607929","_cell_guid":"decd9920-8ff4-4a82-babe-033d1249a358","trusted":true}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"_uuid":"aed47871-2d46-4b6f-8647-03368eabdd11","_cell_guid":"5562fa5e-a996-4f4c-baf0-768064ede725","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-03-07T16:47:09.582632Z","iopub.execute_input":"2023-03-07T16:47:09.583021Z","iopub.status.idle":"2023-03-07T16:47:25.028816Z","shell.execute_reply.started":"2023-03-07T16:47:09.582967Z","shell.execute_reply":"2023-03-07T16:47:25.027470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"print(\"load jax\")\nimport jax\nprint(\"JAX version \" + jax.__version__)\nprint(\"JAX \" + jax.__file__)\nprint(jax.device_count())\nprint(jax.devices())\nprint(jax.numpy.add(1, 1))","metadata":{"execution":{"iopub.status.busy":"2022-09-16T16:41:55.328687Z","iopub.execute_input":"2022-09-16T16:41:55.329544Z","iopub.status.idle":"2022-09-16T16:42:04.143932Z","shell.execute_reply.started":"2022-09-16T16:41:55.329447Z","shell.execute_reply":"2022-09-16T16:42:04.143031Z"}}},{"cell_type":"markdown","source":"print(\"load torch\")\nimport torch_xla\nprint(\"Torch version \" + torch_xla.__version__)\nprint(\"Torch \" + torch_xla.__file__)\n\nimport torch_xla.core.xla_model as xm\nprint(xm.xla_device())\n\nimport torch\nt = torch.randn(2, 2, device=xm.xla_device())\nprint(t.device)\nprint(t)","metadata":{"execution":{"iopub.status.busy":"2022-09-16T16:30:45.095894Z","iopub.execute_input":"2022-09-16T16:30:45.096839Z"}}}]}