{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-03T06:57:11.010634Z","iopub.execute_input":"2022-08-03T06:57:11.011063Z","iopub.status.idle":"2022-08-03T06:57:11.026914Z","shell.execute_reply.started":"2022-08-03T06:57:11.011013Z","shell.execute_reply":"2022-08-03T06:57:11.025468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Attempted implementation of the Vision Transformer (basic model) based on the Keras Documentation example.\n### Hyperparameters: Embedding size 512, num transformer blocks 64, num heads 16, patch size 8x8, upscaling of the mnist dataset 80/28x which is upscale each image to 80px by 80px\n#### **Expected accuracy: 98%+**\n\n#### Hope the code to be self-explanatory with a few comment here and there","metadata":{}},{"cell_type":"code","source":"!pip install --upgrade pip\n!pip install --upgrade \"jax[cpu]\"\n!pip install --upgrade optax einops\n!pip install --upgrade git+https://github.com/deepmind/dm-haiku\nimport functools as ft\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nimport jax\nimport jax.nn as jnn\nimport jax.random as jr\nimport jax.numpy as jnp\n\nfrom jax.scipy.special import logsumexp\n\nimport optax\n\nimport einops\n\nimport haiku as hk\nimport haiku.initializers as hki\nfrom tqdm import tqdm","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:59:53.014634Z","iopub.execute_input":"2022-08-03T06:59:53.015127Z","iopub.status.idle":"2022-08-03T07:01:17.722621Z","shell.execute_reply.started":"2022-08-03T06:59:53.015036Z","shell.execute_reply":"2022-08-03T07:01:17.721391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    # Disable all GPUS\n    tf.config.set_visible_devices([], 'GPU')\n    tf.config.set_visible_devices([], 'TPU')\n    visible_devices = tf.config.get_visible_devices()\n    print(visible_devices)\n    for device in visible_devices:\n        assert device.device_type != 'GPU' and device.device_type != 'TPU'\nexcept:\n    # Invalid device or cannot modify virtual devices once initialized.\n    print(\"Cannot change virtual devices\")","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:01:35.848676Z","iopub.execute_input":"2022-08-03T07:01:35.849700Z","iopub.status.idle":"2022-08-03T07:01:36.056532Z","shell.execute_reply.started":"2022-08-03T07:01:35.849658Z","shell.execute_reply":"2022-08-03T07:01:36.055297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dataset(filename='/kaggle/input/digit-recognizer/train.csv', filename1='/kaggle/input/digit-recognizer/test.csv'):\n    train_data = pd.read_csv(filename)\n    test = pd.read_csv(filename1).values[:, :]\n\n    train_y = train_data.values[:, 0]\n    train_x = train_data.values[:, 1:]\n\n    train_x = (train_x - 128.0) / 255.0\n    test = (test - 128.0) / 255.0\n\n    train_x = train_x.reshape((-1, 28, 28, 1))\n    test_x = test.reshape((-1, 28, 28, 1))\n\n    return train_x, train_y, test_x\n","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:01:59.662930Z","iopub.execute_input":"2022-08-03T07:01:59.663326Z","iopub.status.idle":"2022-08-03T07:01:59.671005Z","shell.execute_reply.started":"2022-08-03T07:01:59.663293Z","shell.execute_reply":"2022-08-03T07:01:59.669674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Upscale the training and test datasets\nupscale = 80\n\ntrain_x, train_y, test_x = load_dataset()\n\ntrain_res = np.zeros((train_x.shape[0], upscale, upscale, 1))\n\nprint(\"Computing train data upscaling.................\")\n\nfor i in range(train_res.shape[0]):\n    train_res[i, :, :, :] = np.array(tf.image.resize(tf.convert_to_tensor([train_x[i]]), size=(upscale, upscale)))\n\ntest_res = np.zeros((test_x.shape[0], upscale, upscale, 1))\n\nprint(\"Computing test data upscaling.................\")\nfor j in range(test_res.shape[0]):\n    test_res[j, :, :, :] = np.array(tf.image.resize(tf.convert_to_tensor([test_x[j]]), size=(upscale, upscale)))\n\ndata = {\"train\": train_res, \"labels\": train_y, \"test\": test_res}\n\n#with open('/kaggle/data2.dict', 'wb') as f:\n#    pickle.dump(data, f)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:02:03.179086Z","iopub.execute_input":"2022-08-03T07:02:03.180017Z","iopub.status.idle":"2022-08-03T07:03:35.831751Z","shell.execute_reply.started":"2022-08-03T07:02:03.179971Z","shell.execute_reply":"2022-08-03T07:03:35.830649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = data['train']\ny = data['labels']\nxt = data['test']","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:04:11.308145Z","iopub.execute_input":"2022-08-03T07:04:11.308540Z","iopub.status.idle":"2022-08-03T07:04:11.313893Z","shell.execute_reply.started":"2022-08-03T07:04:11.308505Z","shell.execute_reply":"2022-08-03T07:04:11.312563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Keras implementation of the patch \"maker\" using Tensorflow","metadata":{}},{"cell_type":"code","source":"class PreProcessPatches:\n    def __init__(self, patch_size):\n        self.patch_size = patch_size\n\n    def __call__(self, images):\n        with tf.device('/CPU:0'):\n            batch_size = images.shape[0]\n            patches = tf.image.extract_patches(\n                images=images,\n                sizes=[1, self.patch_size, self.patch_size, 1],\n                strides=[1, self.patch_size, self.patch_size, 1],\n                rates=[1, 1, 1, 1],\n                padding=\"VALID\"\n            )\n            patch_dims = patches.shape[-1]\n            patches = tf.reshape(patches, [batch_size, -1, patch_dims])\n        return jnp.array(patches.numpy(), dtype=jnp.float32)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:04:14.492263Z","iopub.execute_input":"2022-08-03T07:04:14.493068Z","iopub.status.idle":"2022-08-03T07:04:14.501151Z","shell.execute_reply.started":"2022-08-03T07:04:14.493026Z","shell.execute_reply":"2022-08-03T07:04:14.499901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Vision Transformer modules implementation","metadata":{}},{"cell_type":"code","source":"class PatchEncoder(hk.Module):\n    def __init__(self, num_patches, projection_dim=1024):\n        super(PatchEncoder, self).__init__()\n        self.num_patches = num_patches\n        self.projection_dim = projection_dim\n        self.positions = jnp.arange(0, self.num_patches, step=1)\n\n    def __call__(self, patch):\n        w_init = hki.VarianceScaling()\n        b_init = hki.Constant(0)\n        return hk.Linear(output_size=self.projection_dim, w_init=w_init, b_init=b_init, name=\"projection\")(patch) + \\\n               hk.Embed(vocab_size=self.num_patches, embed_dim=self.projection_dim, w_init=w_init,\n                        name=\"position_embed\")(self.positions)\n","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:04:16.708990Z","iopub.execute_input":"2022-08-03T07:04:16.710168Z","iopub.status.idle":"2022-08-03T07:04:16.720581Z","shell.execute_reply.started":"2022-08-03T07:04:16.710125Z","shell.execute_reply":"2022-08-03T07:04:16.718378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MLP(hk.Module):\n    def __init__(self, hidden_units, dropout):\n        super(MLP, self).__init__()\n        self.hidden_units = hidden_units\n        self.dropout = dropout\n\n    def __call__(self, x, *, is_training: bool):\n        dropout = self.dropout if is_training else 0.0\n        w_init = hki.VarianceScaling()\n        b_init = hki.Constant(0)\n        for units in self.hidden_units:\n            x = hk.Linear(units, w_init=w_init, b_init=b_init)(x)\n            x = jnn.gelu(x, approximate=False)\n            x = hk.dropout(hk.next_rng_key(), dropout, x)\n        return x\n","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:05:03.682011Z","iopub.execute_input":"2022-08-03T07:05:03.682392Z","iopub.status.idle":"2022-08-03T07:05:03.691907Z","shell.execute_reply.started":"2022-08-03T07:05:03.682360Z","shell.execute_reply":"2022-08-03T07:05:03.690742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ViT(hk.Module):\n    def __init__(self, num_patches=10 * 10, projection_dim=1024, num_blocks=8, num_heads=8, transformer_units_1=2048,\n                 transformer_units_2=1024, mlp_head_units=(2048, 1024), dropout=0.5):\n        super(ViT, self).__init__()\n        self.num_patches = num_patches\n        self.projection_dim = projection_dim\n        self.num_blocks = num_blocks\n        self.num_heads = num_heads\n        self.transformer_units_1 = transformer_units_1\n        self.transformer_units_2 = transformer_units_2\n        self.mlp_head_units = mlp_head_units\n        self.dropout = dropout\n        self.norm = lambda: hk.LayerNorm(axis=-1, create_scale=True, create_offset=True, eps=1e-6,\n                                         scale_init=hki.Constant(1.0), offset_init=hki.Constant(0.0))\n\n    def __call__(self, patches, *, is_training: bool):\n        dropout = self.dropout if is_training else 0.0\n\n        encoded_patches = PatchEncoder(self.num_patches, self.projection_dim)(patches)\n\n        for _ in range(self.num_blocks):\n            x1 = self.norm()(encoded_patches)\n            attention = hk.MultiHeadAttention(self.num_heads, self.projection_dim // self.num_heads,w_init_scale=1.0)(x1,x1,x1)\n            x2 = attention + encoded_patches\n            x3 = self.norm()(x2)\n            x3 = MLP((self.transformer_units_1, self.transformer_units_2), self.dropout)(x3, is_training=is_training)\n\n            encoded_patches = x3 + x2\n\n        representation = self.norm()(encoded_patches)\n        representation = einops.rearrange(representation, 'b h t -> b (h t)')\n        representation = hk.dropout(hk.next_rng_key(), dropout, representation)\n\n        features = MLP(self.mlp_head_units, self.dropout)(representation, is_training=is_training)\n\n        logits = hk.Linear(10)(features)\n\n        return logits - logsumexp(logits, axis=1, keepdims=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:05:07.714243Z","iopub.execute_input":"2022-08-03T07:05:07.714664Z","iopub.status.idle":"2022-08-03T07:05:07.728929Z","shell.execute_reply.started":"2022-08-03T07:05:07.714624Z","shell.execute_reply":"2022-08-03T07:05:07.727733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"patch_size = 8\npatch_dim = 80 // patch_size\ndef build_forward_fn(num_patches=patch_dim * patch_dim, projection_dim=512, num_blocks=64, num_heads=16,\n                     transformer_units_1=2048, transformer_units_2=512, mlp_head_units=(2048, 512), dropout=0.4):\n    def forward_fn(dgt: jnp.ndarray, *, is_training: bool) -> jnp.ndarray:\n        return ViT(num_patches=num_patches, projection_dim=projection_dim,\n                   num_blocks=num_blocks, num_heads=num_heads, transformer_units_1=transformer_units_1,\n                   transformer_units_2=transformer_units_2, mlp_head_units=mlp_head_units,\n                   dropout=dropout)(dgt, is_training=is_training)\n    return forward_fn","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:05:12.919042Z","iopub.execute_input":"2022-08-03T07:05:12.919419Z","iopub.status.idle":"2022-08-03T07:05:12.927981Z","shell.execute_reply.started":"2022-08-03T07:05:12.919388Z","shell.execute_reply":"2022-08-03T07:05:12.926671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Define loss function to apply during training. We'll consider for now just cross_entropy and regularization of parameters","metadata":{}},{"cell_type":"code","source":"def focal_loss(labels, y_pred, ce, gamma, alpha):\n    weight = labels * jnp.power(1 - y_pred, gamma)\n    f_loss = alpha * (weight * ce)\n    f_loss = jnp.sum(f_loss, axis=1)\n    f_loss = jnp.mean(f_loss, axis=0)\n    return f_loss\n\n\n@ft.partial(jax.jit, static_argnums=(0, 6))\ndef ce_loss_fn(forward_fn, params, state, rng, a, b, num_classes: int = 10):\n    logits, state = forward_fn(params, state, rng, a)\n\n    labels = einops.rearrange(b, 'b l -> (b l)')\n    labels = jnn.one_hot(labels, num_classes=num_classes)\n    labels = optax.smooth_labels(labels, 2e-2)\n\n    # Weight decay\n    l2_loss = 0.5 * jnp.mean(jnp.array([jnp.sum(jnp.square(p)) for p in jax.tree_util.tree_leaves(params)], dtype=jnp.float32))\n    l1_loss = jnp.mean(jnp.array([jnp.sum(jnp.abs(p)) for p in jax.tree_util.tree_leaves(params)], dtype=jnp.float32))\n\n    # Normalized CE loss and Focal loss so it is more smooth and gives back better feedback\n    # logits = jnp.clip(logits, a_min=jnp.log(1e-12), a_max=jnp.log(1 - 1e-12))\n    ce = -labels * logits\n\n    \n    # CE loss\n    ce_loss = jnp.sum(ce, axis=1)\n    ce_loss = jnp.mean(ce_loss, axis=0)\n\n    # y_pred = jnp.exp(logits)\n    # Focal Loss\n    #f_loss = focal_loss(labels, y_pred, ce, 2.0, 4.0) # + focal_loss(labels, y_pred, ce, 3.0, 4.0) # + focal_loss(labels, y_pred, ce, 4.0, 4.0)\n\n    # Double Soft F1 Loss\n    # tp = jnp.sum(labels * y_pred, axis=0)\n    # fp = jnp.sum((1 - labels) * y_pred, axis=0)\n    # fn = jnp.sum(labels * (1 - y_pred), axis=0)\n    # tn = jnp.sum((1 - labels) * (1 - y_pred), axis=0)\n    # soft_f11 = 2 * tp / (2 * tp + fn + fp + 1e-16)\n    # soft_f10 = 2 * tn / (2 * tn + fn + fp + 1e-16)\n    # cost1 = 1 - soft_f11\n    # cost0 = 1 - soft_f10\n    # f1_loss = jnp.mean(0.5 * (cost1 + cost0))\n\n    # soft f1 score loss + focal loss and weight decay and l1 loss\n    return ce_loss + 1e-10 * (l2_loss + l1_loss), state","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:05:19.142461Z","iopub.execute_input":"2022-08-03T07:05:19.142989Z","iopub.status.idle":"2022-08-03T07:05:19.167758Z","shell.execute_reply.started":"2022-08-03T07:05:19.142948Z","shell.execute_reply":"2022-08-03T07:05:19.166188Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## We'll also define the batch generator for each epoch shuffling data randomly","metadata":{}},{"cell_type":"code","source":"def process_epoch_gen(a, b, batch_size, patch_size, num_devices):\n    proc = PreProcessPatches(patch_size=patch_size)\n\n    topo = batch_size // num_devices\n\n    def epoch_generator(rng):\n        n = a.shape[0]\n        num_batches = n // batch_size\n        key, rng = jr.split(rng)\n\n        perm = jr.permutation(key, n, axis=0)\n        for i in range(num_batches):\n            i0 = i * batch_size\n            i1 = (i + 1) * batch_size\n            subp = perm[i0:i1]\n            outx = jnp.array(proc(a[subp, :, :, :]), dtype=jnp.float32)\n            c = np.expand_dims(b, axis=1)\n            outy = jnp.array(c[subp, :], dtype=jnp.int32)\n            yield outx.reshape(num_devices, topo, *outx.shape[1:]), outy.reshape(num_devices, topo, *outy.shape[1:])\n\n    return epoch_generator","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:05:24.967719Z","iopub.execute_input":"2022-08-03T07:05:24.968950Z","iopub.status.idle":"2022-08-03T07:05:24.982276Z","shell.execute_reply.started":"2022-08-03T07:05:24.968901Z","shell.execute_reply":"2022-08-03T07:05:24.981268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## We'll also define a class combining methods to instantiate and make an optimization step","metadata":{}},{"cell_type":"code","source":"class ParamsUpdater:\n    def __init__(self, net_init, loss, optimizer: optax.GradientTransformation):\n        self._net_init = net_init\n        self._loss = loss\n        self._opt = optimizer\n\n    def init(self, main_rng, x):\n        out_rng, init_rng = jax.random.split(main_rng)\n        params, state = self._net_init(init_rng, x, is_training=False)\n        opt_state = self._opt.init(params)\n        return jnp.array(0), out_rng, params, state, opt_state\n\n    def update(self, num_steps, rng, params, state, opt_state, bx: jnp.ndarray, by: jnp.ndarray):\n        rng, new_rng = jax.random.split(rng)\n\n        (loss, state), grads = jax.value_and_grad(self._loss, has_aux=True)(params, state, rng, bx, by)\n\n        grads = jax.lax.psum(grads, axis_name='devices')\n\n        updates, opt_state = self._opt.update(grads, opt_state, params)\n\n        params = optax.apply_updates(params, updates)\n\n        metrics = {\n            'step': num_steps,\n            'loss': loss,\n        }\n\n        return num_steps + 1, new_rng, params, state, opt_state, metrics","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:06:43.215521Z","iopub.execute_input":"2022-08-03T07:06:43.216325Z","iopub.status.idle":"2022-08-03T07:06:43.229046Z","shell.execute_reply.started":"2022-08-03T07:06:43.216284Z","shell.execute_reply":"2022-08-03T07:06:43.227906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# We'll start by implementing the training loop finally","metadata":{}},{"cell_type":"code","source":"batch_size = 8\nnum_devices = jax.local_device_count()\nprint(num_devices)\nprocess_gen = process_epoch_gen(x, y, batch_size, patch_size, num_devices)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:06:55.511936Z","iopub.execute_input":"2022-08-03T07:06:55.512654Z","iopub.status.idle":"2022-08-03T07:06:55.664055Z","shell.execute_reply.started":"2022-08-03T07:06:55.512606Z","shell.execute_reply":"2022-08-03T07:06:55.662885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# transform the impure forward function to a pure function pair ffn\nffn = build_forward_fn()\n\nffn_stats = hk.transform_with_state(ft.partial(ffn, is_training=False))\n\nffn = hk.transform_with_state(ffn)\n\napply = ffn.apply\n\nl_apply = ft.partial(apply, is_training=True)\nl_apply = jax.jit(l_apply)\ntest_apply = ft.partial(apply, is_training=True)\ntest_apply = jax.jit(test_apply)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:07:00.458625Z","iopub.execute_input":"2022-08-03T07:07:00.459673Z","iopub.status.idle":"2022-08-03T07:07:00.467509Z","shell.execute_reply.started":"2022-08-03T07:07:00.459626Z","shell.execute_reply":"2022-08-03T07:07:00.466342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rng = jr.PRNGKey(101)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T07:07:04.296247Z","iopub.execute_input":"2022-08-03T07:07:04.296752Z","iopub.status.idle":"2022-08-03T07:07:05.116715Z","shell.execute_reply.started":"2022-08-03T07:07:04.296709Z","shell.execute_reply":"2022-08-03T07:07:05.115522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_fn = ft.partial(ce_loss_fn, l_apply)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.208737Z","iopub.status.idle":"2022-08-03T06:58:17.209186Z","shell.execute_reply.started":"2022-08-03T06:58:17.208960Z","shell.execute_reply":"2022-08-03T06:58:17.208982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Left out some comments in order to make it faster to switch optimizers\nlearning_rate = 5e-5\ngrad_clip_value = 1.0\n# scheduler = optax.exponential_decay(init_value=learning_rate, transition_steps=6000, decay_rate=0.99)\n\noptimizer = optax.chain(\n    optax.adaptive_grad_clip(grad_clip_value),\n    # optax.sgd(learning_rate=learning_rate, momentum=0.99, nesterov=True),\n    #optax.scale_by_radam(b1=0.9, eps=1e-4),\n    optax.scale_by_adam(),\n    # optax.scale_by_yogi(),\n    # optax.scale_by_schedule(scheduler),\n    optax.scale(-learning_rate)\n)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.210125Z","iopub.status.idle":"2022-08-03T06:58:17.210612Z","shell.execute_reply.started":"2022-08-03T06:58:17.210354Z","shell.execute_reply":"2022-08-03T06:58:17.210378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"updater = ParamsUpdater(ffn.init, loss_fn, optimizer)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.212096Z","iopub.status.idle":"2022-08-03T06:58:17.212532Z","shell.execute_reply.started":"2022-08-03T06:58:17.212291Z","shell.execute_reply":"2022-08-03T06:58:17.212313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Initializing parameters..........................\")\nrng1, rng2, rng3, rng = jr.split(rng, 4)\n\nepoch_gen_temp = process_gen(rng1)\nbx, _ = next(epoch_gen_temp)\nb = jnp.expand_dims(bx[0, 0, :, :], axis=0)\n\n\nnum_steps, _, params, state, opt_state = updater.init(rng2, b)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.213789Z","iopub.status.idle":"2022-08-03T06:58:17.214135Z","shell.execute_reply.started":"2022-08-03T06:58:17.213954Z","shell.execute_reply":"2022-08-03T06:58:17.213976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Summarize network parameters\nprint('Network Summary.......................')\nprint(hk.experimental.tabulate(ffn_stats)(b))","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.215097Z","iopub.status.idle":"2022-08-03T06:58:17.215444Z","shell.execute_reply.started":"2022-08-03T06:58:17.215258Z","shell.execute_reply":"2022-08-03T06:58:17.215282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training loop\nprint(\"Starting training loop..........................\")\nnum_epochs = 4\n\nupd_fn = updater.update\n\nbatch_update = jax.pmap(upd_fn, axis_name='devices', in_axes=0, out_axes=0)\n\nparams = jax.device_put_replicated(params, devices=jax.devices())\nstate = jax.device_put_replicated(state, devices=jax.devices())\nopt_state = jax.device_put_replicated(opt_state, devices=jax.devices())\nnum_steps = jax.device_put_replicated(num_steps, devices=jax.devices())","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.216601Z","iopub.status.idle":"2022-08-03T06:58:17.216959Z","shell.execute_reply.started":"2022-08-03T06:58:17.216750Z","shell.execute_reply":"2022-08-03T06:58:17.216786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_devices = jax.local_device_count()\n\nfor i in range(num_epochs):\n    rng1, rng2, rng = jr.split(rng, 3)\n    rng2 = jax.device_put_replicated(rng2, devices=jax.local_devices())\n    for step, (bx, by) in tqdm(enumerate(process_gen(rng1)), total=42000 // batch_size):\n\n        bbx = []\n        bby = []\n        for k in range(n_devices):\n            bbx.append(bx[k])\n            bby.append(by[k])\n\n        dbx = jax.device_put_sharded(bbx, devices=jax.local_devices())\n        dby = jax.device_put_sharded(bby, devices=jax.local_devices())\n\n        num_steps, rng2, params, state, opt_state, metrics = batch_update(num_steps, rng2, params, state, opt_state, dbx, dby)\n        if (step + 1) % 8 == 0:\n            print(f\"......Epoch {i} | Step {step} | Metrics\\n\\n{metrics} .....................................\")","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.218484Z","iopub.status.idle":"2022-08-03T06:58:17.219046Z","shell.execute_reply.started":"2022-08-03T06:58:17.218870Z","shell.execute_reply":"2022-08-03T06:58:17.218891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Starting evaluation loop........................\")\nparams = jax.device_get(jax.tree_util.tree_map(lambda g: g[0], params))\nstate = jax.device_get(jax.tree_util.tree_map(lambda g: g[0], state))\n\nres = np.zeros(xt.shape[0], dtype=np.int64)\n\nbtchs = 10\ncount = xt.shape[0] // bts\n\nproc = PreProcessPatches(patch_size=patch_size)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.220151Z","iopub.status.idle":"2022-08-03T06:58:17.220493Z","shell.execute_reply.started":"2022-08-03T06:58:17.220322Z","shell.execute_reply":"2022-08-03T06:58:17.220343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for j in tqdm(range(count)):\n    rng, = jr.split(rng, 1)\n    a, b = j * btchs, (j + 1) * btchs\n    pbt = proc(xt[a:b, :, :, :])\n    logits, _ = fast_apply(params, state, rng, pbt, is_training=False)\n    res[a:b] = np.array(jnp.argmax(jnp.exp(logits), axis=1), dtype=np.int64)\n","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.221479Z","iopub.status.idle":"2022-08-03T06:58:17.221815Z","shell.execute_reply.started":"2022-08-03T06:58:17.221626Z","shell.execute_reply":"2022-08-03T06:58:17.221647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.DataFrame({'ImageId': np.arange(1, n1 + 1, dtype=np.int64), 'Label': res})\n\ndf.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T06:58:17.223045Z","iopub.status.idle":"2022-08-03T06:58:17.223402Z","shell.execute_reply.started":"2022-08-03T06:58:17.223216Z","shell.execute_reply":"2022-08-03T06:58:17.223251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**The results were submitted via upload. I couldn't get the TPU or GPU to play nice with JAX, maybe it's not good on my end on something. If done accordingly they should round 98%, since via upload that's what it yielded with 2 3090 training it in parallel**","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}