Title of Competition
stringclasses 343
values | Title of Writeup
stringlengths 6
139
| User
stringclasses 1
value | Writeup
stringlengths 419
80.4k
|
---|---|---|---|
Global Wheat Detection | [34th Place Solution using single EfficientDet + Pseudo Labeling] | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Global Wheat Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Sure! I've updated the description with links to public notebooks.</p>
<p><a href="https://www.kaggle.com/brandonnova" target="_blank">@brandonnova</a> Thanks!</p>
<p><a href="https://www.kaggle.com/brendan45774" target="_blank">@brendan45774</a> Thanks!</p>
<p><a href="https://www.kaggle.com/piantic" target="_blank">@piantic</a> Thanks!</p>
<p>Yes it was single model PL. The baseline was really good and I didn't change it much. I just trained on entire dataset as I wanted to use it in PL. The main change I did was in PL training though. I used same augmentations which I used in training (changing augmentations reduced my score). And even no data cleaning! So I think model might be underfitting the training data but generalized comparatively well. P.S This was my first object detection competition and this was completely unexpected!</p>
<p>First of all Congratulation to all, especially to the prize winner and gold medalists and thanks to the organizers for this interesting competition!</p>
<p>So here is our solution to this competition (Very very basic):</p>
<h2>Training</h2>
<ul>
<li>Single EfficientDetD5 (Thanks to <a href="https://www.kaggle.com/shonenkov" target="_blank">@shonenkov</a> for his great notebook)</li>
<li>40 epochs using full dataset (No CV)</li>
<li>Image size: 512 * 512</li>
<li>Augmentations: Random Crop, Random Cutout, Hue Saturation Value, Brightness Random Brightness Contrast, Random Horizontal and Vertical flips and random Cutmix.</li>
<li>Training notebook: <a href="https://www.kaggle.com/kaushal2896/gwd-efficientdet-training-on-entire-dataset" target="_blank">https://www.kaggle.com/kaushal2896/gwd-efficientdet-training-on-entire-dataset</a></li>
</ul>
<h2>Pseudo Labeling</h2>
<ul>
<li>Pseudo labeled the above model with 10 epochs (Thanks to <a href="https://www.kaggle.com/nvnnghia" target="_blank">@nvnnghia</a> for his work)</li>
<li>Used the same augmentations even while pseudo labeling: Random Crop, Random Cutout, Hue Saturation Value, Brightness Random Brightness Contrast, Random Horizontal and Vertical flips and random Cutmix.</li>
<li>Same image size: 512 * 512.</li>
<li>Used both TTA and WBF for final predictions.</li>
<li>Pseudo Labeling notebook: <a href="https://www.kaggle.com/kaushal2896/efficientdet-pseudo-labeling-wbf-tta" target="_blank">https://www.kaggle.com/kaushal2896/efficientdet-pseudo-labeling-wbf-tta</a></li>
</ul>
<h2>What didn't work for us?</h2>
<ul>
<li>Custom augmentations like mixup.</li>
<li>Training on larger image sizes without Random crop augmentation.</li>
<li>Same solution with EfficientDetD6.</li>
<li>Training on higher number of epochs.</li>
<li>FasterRCNN with ResNet51 and ResNet101.</li>
</ul>
<p>Here are different approaches I've tried during this competition: <a href="https://github.com/Kaushal28/Global-Wheat-Detection" target="_blank">https://github.com/Kaushal28/Global-Wheat-Detection</a></p> |
Global Wheat Detection | [42nd place solution] | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Global Wheat Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks for your suggestion <a href="/aidynub">@aidynub</a> </p>
<p>No, I didn't</p>
<p>Here is one of my experiments nearly 2 months ago using fasterRCNN<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2545270%2F693038ebe35bee667f43fdb798263338%2FScreenshot%20from%202020-08-07%2016-10-52.png?generation=1596784304454586&alt=media" alt=""><br>
after this experiment, SPIKE dataset is my best friend.</p>
<p>by trial-error. FasterRCNN gives a better result than D5</p>
<p>Congratulation to all, especially to the prize winner and gold medalists and thanks to the organizers for this interesting competition.<br>
So here are some essential points of our solutions (I will update more detail later)<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2545270%2F4c4ce442608f2f655f7182babf7a7bca%2FUntitled%20Diagram%20(2).png?generation=1596588070622865&alt=media" alt=""><br>
<strong>1. Validation strategy</strong><br>
I use a fixed validation set from the beginning of the competition (663 images). The validation data is from usask_1 and a part of other sources.<br>
<strong>2. Augmentation</strong></p>
<p>2.1. My custom augmentation: <br>
- crop and pad: I realize that the boxes at the border after cropping is not good. Then I remove all the boxes at the border and remove the image content inside the boxes too.<br>
- crop and resize<br>
- resize and pad<br>
- <a href="https://www.cs.tau.ac.il/~turkel/imagepapers/ColorTransfer.pdf" target="_blank">Color Transfer between Images</a><br>
- mixup: Instead of mixup 2 images in training set, I use 1 image in training set and 1 image without wheat head. <br>
- Rotation: random rotate images and use pseudo label as ground truth.</p>
<p>2.2. Albumentation:<br>
- A.HorizontalFlip(p=0.5),<br>
- A.VerticalFlip(p=0.5),<br>
- A.RandomRotate90(p=0.5), <br>
I don't use mosaic augmentation because it does not want to cooperate with my custom augmentation.<br>
<strong>3. SPIKE dataset:</strong> I use WBF on pseudo label and provided ground truth label.<br>
<strong>4. Results</strong><br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2545270%2F9312433df689b4ebe397f0674b067b9b%2FUntitled.png?generation=1596632145633431&alt=media" alt=""></p>
<p>P/s: Is there a chance for us to move into gold zone after verifying solution? </p>
<p>Thanks <a href="/piantic">@piantic</a>
- I retrain fasterRCNN for 7 epochs. I use time tracking on my notebook, so my notebook will stop the training process whenever my notebook meets the time limit (I set it to 5 hours)
- I kept a fixed validation set at the beginning of the competition (663 images). The validation data is from usask_1 and a part of other sources.</p>
<p>resnet152</p>
<p>Thank <a href="/matthewmasters">@matthewmasters</a> Thanks for your huge contribution in this competition. Yes I use an ensemble of EffDet models for the pseudolabel prediction and FasterRCNN for retraining. </p>
<p>detail updated!</p>
<ul>
<li>FasterRCNN 0.7582, </li>
<li>D0: 0.7605</li>
<li>D5 (512x512): 7584</li>
<li>D5 (768x768): I didn't check LB score. But I know it is good because of high CV score.</li>
</ul>
<p>I will update more detail later. </p>
<p>I ignore images without bboxes. Just remember to add an empty string to submission file.</p>
<p>TTA only</p> |
Global Wheat Detection | [80th place solution😂] Source-separated Psuedo Labeling | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Global Wheat Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks! The idea is simple but is quite complicated to implement.. ;)</p>
<p>Thank you!</p>
<p>Thank you!</p>
<p>Big thanks to the whole team ;)</p>
<p>Thanks for the warm words! Let's see after the YOLO subs are removed..</p>
<p>First of all, thanks for the host for holding this competition! </p>
<p>And great thanks to our team members, <a href="https://www.kaggle.com/datahobbit" target="_blank">@datahobbit</a>, <a href="https://www.kaggle.com/ratthachat" target="_blank">@ratthachat</a>, <a href="https://www.kaggle.com/yashchoudhary" target="_blank">@yashchoudhary</a>, <a href="https://www.kaggle.com/nitindatta" target="_blank">@nitindatta</a> and it was a pleasure teaming up. Everyone played a great part in the solutions which <a href="https://www.kaggle.com/ratthachat" target="_blank">@ratthachat</a> elaborates! It was fun having discussions and everybody was a great analyst/coder. We did a great job and made it into the TOP-2% ;)</p>
<p>This is our solution of our team Wheat Fields!</p>
<p>(I will come back to update with the details.)</p>
<h2>Models</h2>
<ul>
<li>Model: EffdetD5 2 folds ensemble </li>
</ul>
<p>We evaluated our CV based on data source separated CV with original weightings.</p>
<h2>Source separated psuedo labeling</h2>
<h3>Idea</h3>
<p>We were scared that psuedo labeling with the entire test set prior will overfit to the UTokyo data which should be 70% of the test data. With this source-split, we can train model which overfit to UTokyo and other model to the rest, maximizing the PB.</p>
<h3>Step.1</h3>
<p>Predict on test set using Best CV Model and split the test set to two: TestSetB :UToyko which image has <code>number of wheats <39</code> and TestSetC: <code>number of wheats>=39</code>. We save the labels for psuedo label as well</p>
<h3>Step2:</h3>
<p>train two models --> Model-B train with pseudo [TestSetB, traindata] and Model-C train with pseudo [TestSetC,traindata].</p>
<h3>Inference:</h3>
<p>Predict TestSetB with Model-B and TestSetC with Model-C.</p>
<h1>Codes!</h1>
<p>I uploaded my training codes here.<br>
<a href="https://github.com/kentaroy47/kaggle-wheat-arutema47" target="_blank">https://github.com/kentaroy47/kaggle-wheat-arutema47</a></p> |
Global Wheat Detection | [From 447 to 135th place Solution] EfficientDet Ensemble | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Global Wheat Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks, you're welcome :D</p>
<p>Thanks!
I used batch 1 and Google Colab (P100).</p>
<p><a href="/nvnnghia">@nvnnghia</a> thanks :D</p>
<p>Congratulations to all the winners and to all the players that learnt new things!</p>
<p>Since the start of the competition we have used FasterRCNN then Shifted to EfficientDet then Shifted to YOLOv5. Then used a combination of both EfficientDet+YOLOv5. When we knew that YOLOv5 is prohibited we turned back to EfficientDet and kept optimizing it.</p>
<p><strong>Training</strong><br>
Data Cleaning: </p>
<ul>
<li>Deleted tiny bounding boxes (width or height under a certain threshold)</li>
<li>Deleted hunge bounding boxes (width or height over a certain threshold)</li>
</ul>
<p>Data Augmentation: </p>
<ul>
<li>Online Augmentations</li>
<li>Flips & Rotations (90 multiples)</li>
<li>Crop & Resize</li>
<li>Hue Saturation Contrast Brightness </li>
<li>Moving Blur </li>
<li>Noise Injection (Gaussian Noise)</li>
<li>Cutout (Made different versions of that) </li>
<li>Cutmix </li>
</ul>
<p>Training Process: </p>
<ul>
<li>Used EfficientDet5 (& EfficientDet7)</li>
<li>Used both 512x512 and 1024x1024 images</li>
<li>Startified 5 Folds Splitting </li>
<li>By Source Splitting (for some Fine Tuning)</li>
<li>Manual tweaks when training the models (& Early Stopping)</li>
<li>Change Augmentation distributions every certain number of epochs</li>
</ul>
<p><strong>Inference</strong><br>
A picture is worth a thousand words:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F1739631%2F7dffedb28611b84b7c76165e8873215d%2Fstar.png?generation=1596624192299446&alt=media" alt=""></p>
<p>Here you find my inference <a href="https://www.kaggle.com/ffares/ensemble-models-tta-efficientdet-512-1024" target="_blank">kernel</a>, please upvote the notebook if you like it, and most imprtantly feel free to give your feedback so I can learn from my mistakes. </p>
<p>I want to thank the hosts of this competition, kaggle and all the participants who submitted compliant solutions. Special thanks goes for <a href="https://www.kaggle.com/shonenkov" target="_blank">@shonenkov</a> <a href="https://www.kaggle.com/nvnnghia" target="_blank">@nvnnghia</a> <a href="https://www.kaggle.com/pestipeti" target="_blank">@pestipeti</a> and many others who kept sharing during the competition.</p>
<p>We will update with further details.</p> |
Global Wheat Detection | [Update ] The 9th place solution with code | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Global Wheat Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Unfortunately, during the competition, we did not check the individual impact of this feature on the public score. I can only say that the metric on validation did not decrease. I'll write if I check it in the future.</p>
<p>We didn't use Retinanet and YOLO to build the ensemble. We used DetectoRS and UniverseNet</p>
<p>We trained models on 4/5 of the dataset and validated on 1/5 </p>
<p>Here are some observations from our submissions:
- Pseudo crops from jigsaw puzzles (DetectoRS R50): 0.7513 -> 0.7582
- Tuning of pseudo labeling parameters for sampling positive examples (ensemble): 0.7709 -> 0.7729
- Pseudo labeling (DetectoRS R50): 0.7582 -> 0.7691
- Pseudo labeling (UniverseNet Res2Net50): 0.7494 -> 0.7627
- SPIKE dataset (DetectoRS R50): 0.7582 -> 0.7592
- Deleting [usask1, ethz1] from pseudo labeling (DetectoRS R50): 0.7678 -> 0.7691</p>
<p>For TTA was used a standard MMDet algorithm with NMS that looks like this for two-stage detectors (DetectoRS):<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2F6c66a60eb785874c2a8ab8a12bc9478c%2FSelection_126.png?generation=1596697435050357&alt=media" alt=""></p>
<p>For one-stage detectors (UniverseNet), the algorithm is similar, only without the part with RoiAlign, Head, etc.</p>
<p>WBF was used only for ensemble of two models.</p>
<p>Thanks! </p>
<p>For DetectoRS (one of the old models): 0.7582 -> 0.7691
For UniverseNet with Res2Net50: 0.7494 -> 0.7627</p>
<p>Yes. I think therefore 1 epoch is enough.</p>
<h1>Introduction</h1>
<p>(This post was jointly written by the winning team, see details below)</p>
<p>First, we wish to express our congratulations to the winners and to all the nominees as well for their remarkable achievements and continued excellence and look forward to exciting times in object detection algorithms.</p>
<p>In addition, many thanks to Kaggle and the organizers for holding this interesting competition. And special thanks to my colleagues <a href="https://www.kaggle.com/orkatz2" target="_blank">@orkatz2</a> (Or Katz) and <a href="https://www.kaggle.com/solomonk" target="_blank">@solomonk</a> (Shlomo Kashani, author of the book “Deep Learning Interviews”).</p>
<h1>Code</h1>
<ul>
<li>training code: <a href="https://github.com/amirassov/kaggle-global-wheat-detection" target="_blank">https://github.com/amirassov/kaggle-global-wheat-detection</a></li>
<li>submission code: <a href="https://www.kaggle.com/amiras/pseudo-ensemble-detectors-3-st-universenet-r10" target="_blank">pseudo ensemble: detectors (3 st)+universenet r10</a></li>
</ul>
<h1>Summary</h1>
<p>Our solution is based on the excellent MMDetection framework (<a href="https://github.com/open-mmlab/mmdetection)" target="_blank">https://github.com/open-mmlab/mmdetection)</a>. We evaluated and tested numerous models in an attempt to find the ones which are better suited for wheat detection. Why? Because there is not always a direct correlation between the COCO mAP score, as reported by the authors of the original models, and the actual mAP on the wheat corpus. Therefore, experimentation was extremely important. Amongst the many models we evaluated in MMDet are: </p>
<ul>
<li>GFocal</li>
<li>ATSS</li>
<li>UniverseNet </li>
<li>DetectorRS </li>
<li>SOLO-v2 (used for segmentation but we experimented with it anyway)</li>
</ul>
<p>We then trained an ensemble of the top-performing models which were: </p>
<ul>
<li>DetectoRS with the ResNet50 backbone (<a href="https://github.com/joe-siyuan-qiao/DetectoRS" target="_blank">https://github.com/joe-siyuan-qiao/DetectoRS</a>)</li>
<li>UniverseNet+GFL with the Res2Net101 backbone (<a href="https://github.com/shinya7y/UniverseNet" target="_blank">https://github.com/shinya7y/UniverseNet</a>)</li>
</ul>
<p>To increase the score a single round of pseudo labelling was applied to each model. Additionally, for a much better generalization of our models, we used heavy augmentations.</p>
<h1>Jigsaw puzzles</h1>
<p>In the original corpus provided by the organizers, the training images were cropped from an original set of larger images. Therefore, we collected and assembled the original puzzles resulting in a corpus of 1330 puzzle images. The puzzle collection algorithm we adopted was based on <a href="https://github.com/lRomul/argus-tgs-salt/blob/master/mosaic/create_mosaic.py" target="_blank">https://github.com/lRomul/argus-tgs-salt/blob/master/mosaic/create_mosaic.py</a>. But we were unsuccessful in collecting the bounding boxes for puzzles. Mainly because of the existence of bounding boxes that are located on or in the vicinity the border of the image. For this reason, we generated crops for the puzzles offline in addition to training images and generated boxes for them using pseudo labelling.</p>
<h1>Validation approach</h1>
<p>We used MultilabelStratifiedKFold with 5 folds (<a href="https://github.com/trent-b/iterative-stratification" target="_blank">https://github.com/trent-b/iterative-stratification</a>) stratified by the number of boxes, a median of box areas and source of images. We guaranteed that there isn’t any leak between the sub-folds, so that the images of one puzzle were used only in that one particular fold.</p>
<p>Referring to the paper <a href="https://arxiv.org/abs/2005.02162" target="_blank">https://arxiv.org/abs/2005.02162</a>, one can see wheat heads from different sources. We assumed that the wheat heads of usask_1, ethz_1 sources are very different from the test sources (UTokyo_1, UTokyo_2, UQ_1, NAU_1). Therefore, we did not use these sources for validation.</p>
<p>However, our validation scores did not correlate well with the Kaggle LB. We only noticed global improvements (for example, DetectoRS is better than UniverseNet). Local improvements such as augmentation parameters, WBF parameters etc. did not correlate. We, therefore, shifted our attention to the LB scores mainly. </p>
<p>We trained our models only on the first fold.</p>
<h1>Augmentations</h1>
<p>Due to the relatively small size of our training set, and another test set distribution, our approach relied heavily on data augmentation. During training, we utilized an extensive data augmentation protocol:</p>
<ul>
<li>Various augmentations from albumentations library (<a href="https://albumentations.ai):" target="_blank">https://albumentations.ai):</a><ul>
<li>HorizontalFlip, ShiftScaleRotate, RandomRotate90</li>
<li>RandomBrightnessContrast, HueSaturationValue, RGBShift</li>
<li>RandomGamma</li>
<li>CLAHE</li>
<li>Blur, MotionBlur</li>
<li>GaussNoise</li>
<li>ImageCompression</li>
<li>CoarseDropout</li></ul></li>
<li>RandomBBoxesSafeCrop. Randomly select N boxes in the image and find their union. Then we cropped the image keeping this unified.</li>
<li>Image colorization (<a href="https://www.kaggle.com/orkatz2/pytorch-pix-2-pix-for-image-colorization" target="_blank">https://www.kaggle.com/orkatz2/pytorch-pix-2-pix-for-image-colorization</a>) </li>
<li>Style transfer (<a href="https://github.com/bethgelab/stylize-datasets)" target="_blank">https://github.com/bethgelab/stylize-datasets)</a>. A random image from a small test (10 images) was used as a style. </li>
<li>Mosaic augmentation. <code>a, b, c, d</code> -- randomly selected images. Then we just do the following:</li>
</ul>
<pre><code>top = np.concatenate([a, b], axis=1)
bottom = np.concatenate([c, d], axis=1)
result = np.concatenate([top, bottom], axis=0)
</code></pre>
<ul>
<li>Mixup augmentation. <code>a, b</code> -- randomly selected images. Then: <code>result = (a + b) / 2</code></li>
<li>Multi-scale Training. In each iteration, the scale of image is randomly sampled from <code>[(768 + 32 * i, 768 + 32 * i) for i in range(25)]</code>.</li>
<li>All augmentations except colorization and style transfer were applied online.<br>
Examples of augmented images:</li>
</ul>
<table>
<thead>
<tr>
<th><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2F54b1605a052bc34520cce5f7ca81f86f%2F0.jpg?generation=1596619282971124&alt=media" alt=""></th>
<th><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2Fe7bad4c91782a5614ee5731f3610e376%2F6.jpg?generation=1596619343754665&alt=media" alt=""></th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2F4dfab25fb6ed84e7ef545c42361382c5%2F27.jpg?generation=1596619635969807&alt=media" alt=""></td>
<td><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2Fcb53ccda22bf16bef104caf9e25459df%2F47.jpg?generation=1596619666130434&alt=media" alt=""></td>
</tr>
</tbody>
</table>
<h1>External data:</h1>
<p>SPIKE dataset: <a href="https://www.kaggle.com/c/global-wheat-detection/discussion/164346" target="_blank">https://www.kaggle.com/c/global-wheat-detection/discussion/164346</a></p>
<h1>Models</h1>
<p>We used DetectoRS with ResNet50 and UniverseNet+GFL with Res2Net101 as main models. DetectoRS was a little bit more accurate and however much slower to train than UniverseNet:</p>
<ul>
<li>Single DetectoRS Public LB score without pseudo labeling: 0.7592</li>
<li>Single UniverseNet Public LB score without pseudo labeling: 0.7567</li>
</ul>
<p>For DetectoRS we used:</p>
<ul>
<li>LabelSmoothCrossEntropyLoss with parameter 0.1</li>
<li>Empirical Attention (<a href="https://github.com/open-mmlab/mmdetection/tree/master/configs/empirical_attention" target="_blank">https://github.com/open-mmlab/mmdetection/tree/master/configs/empirical_attention</a>)</li>
</ul>
<h1>Training pipeline</h1>
<p>In general, we used a multi-stage training pipeline:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2F6b28b3ab6458d9a0763d34c78abf15a0%2FSelection_125.png?generation=1596629231468089&alt=media" alt=""></p>
<h1>Model inference</h1>
<p>We used TTA6 (Test Time Augmentation) for all our models:</p>
<ul>
<li>Multi-scale Testing with scales [(1408, 1408), (1536, 1536)]</li>
<li>Flips: [original, horizontal, vertical]</li>
</ul>
<p>For TTA was used a standard MMDet algorithm with NMS that looks like this for two-stage detectors (DetectoRS):<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F413252%2F6fff06749b880222e0c06bea777b8e84%2FSelection_126.png?generation=1597392868005836&alt=media" alt=""></p>
<p>For one-stage detectors (UniverseNet), the algorithm is similar, only without the part with RoiAlign, Head, etc.</p>
<h1>Pseudo labelling</h1>
<ul>
<li>Sampling positive examples. We predicted the test image and received its scores and the bounding boxes. Then we calculated <code>confidence = np.mean(scores > 0.75)</code>. If the confidence was greater than 0.6 we accepted this image and used for pseudo labelling.</li>
<li>Sources [usask_1, ethz_1] and augmentations like mosaic, mixup, colorization, style transfer weren’t used for pseudo labelling.</li>
<li>1 epoch, 1 round, 1 stage.</li>
<li>Data: original data + 3 x pseudo test data</li>
</ul>
<h1>Ensemble</h1>
<p>We used WBF (<a href="https://github.com/ZFTurbo/Weighted-Boxes-Fusion" target="_blank">https://github.com/ZFTurbo/Weighted-Boxes-Fusion</a>) for the ensemble. The distribution of DetectoRS and UniverseNet scores is different. So we applied scaling using <code>rankdata</code> (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rankdata.html):" target="_blank">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rankdata.html):</a></p>
<pre><code>scaled_scores = 0.5 * (rankdata(scores) / len(scores)) + 0.5.
</code></pre>
<p>WBF parameters:</p>
<ul>
<li>weights=[0.65, 0.35] respectively for models [DetectoRS, UniverseNet]</li>
<li>iou_thr=0.55</li>
<li>score_thr=0.45</li>
</ul>
<h1>Our final submission pipeline (0.7262 on Private LB and 0.7734 on Public LB):</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F413252%2Fc2f34231c3dbffc0e8335b8d9cb15898%2FSelection_120.png?generation=1596619828315578&alt=media" alt=""></p>
<h1>Some observations from our submissions:</h1>
<ul>
<li>Pseudo crops from jigsaw puzzles (DetectoRS R50): 0.7513 -> 0.7582</li>
<li>Tuning of pseudo labeling parameters for sampling positive examples (ensemble): 0.7709 -> 0.7729</li>
<li>Pseudo labeling (DetectoRS R50): 0.7582 -> 0.7691</li>
<li>Pseudo labeling (UniverseNet Res2Net50): 0.7494 -> 0.7627</li>
<li>SPIKE dataset (DetectoRS R50): 0.7582 -> 0.7592</li>
<li>Deleting [usask1, ethz1] from pseudo labeling (DetectoRS R50): 0.7678 -> 0.7691</li>
</ul>
<h1>What we didn’t do:</h1>
<ul>
<li>MMDetection and YOLOV5 ensemble. That was the main goal but since YOLOV5 was disqualified we gave up this option.</li>
<li>MMDetection and EfficientDet ensemble. We only managed to make a submission for the first time on the last day but we could not get a good enough result. We believe that if we had a few more days we could improve the result by tune the WBF parameters.</li>
<li>We stopped improving YOLOV5 about a month before the end of the competition. </li>
</ul>
<h1>What didn’t work:</h1>
<ul>
<li>Wheat Ears Detection Dataset: CV improved, but LB did not.</li>
<li>More than 1 rounds of pseudo labeling with the same model.</li>
<li>Scale-aware testing like this: <a href="https://drive.google.com/file/d/14VwSjMeRZUtisZtqQPmbll6w4zvZXIAQ" target="_blank">https://drive.google.com/file/d/14VwSjMeRZUtisZtqQPmbll6w4zvZXIAQ</a></li>
<li>Rotate90 TTA for DetectoRS and UniverseNet</li>
</ul>
<h1>Acknowledgements</h1>
<p>Thanks to internet service provider HOSTKEY (<a href="https://www.hostkey.com" target="_blank">https://www.hostkey.com</a>) that gave me a grant for access to GPU servers.</p>
<p><strong>The code will be published soon.</strong></p> |
GoDaddy - Microbusiness Density Forecasting | #1 solution - generalization with linear regression | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>:( Not very kaggly, I think.</p>
<p>Did you execute this code? Getting the mbd chg over data from revealed test should be fairly straightforward. </p>
<pre><code>dfc = pd.read_csv()
rt = pd.read_csv().set_index()
dfc[] = dfc[].apply( x:x[-:])
dfc[] = dfc[].apply( x:(x[:x.index()]))
dfc = dfc.reset_index().set_index()
dfc[] = dfc.apply( r:(r[] - rt.loc[, ])/rt.loc[, ], axis = )
display(dfc.groupby().mean()[])
</code></pre>
<p>I admit to being a bit surprised that most folks hadn't already done this sort of EDA. The contest will likely be won by whoever called the macro trend correct, which isn't always in a straight line.</p>
<p>Thanks Nic! Good luck on your results.</p>
<p>I predict all cfips. Manual blacklisting didn't seem to improve my scores, but I also had features which were similar in purpose, such as whether there was a change over some threshold in the last month(s). Rounding on active of course helps as well.</p>
<p>Similar to my long trend prediction, though my may numbers might be a bit aggressive. My seasonal is very aggressive, but I figured why not in case things change dramatically. Also similar to the results I pulled from someone elses prediction.</p>
<p>Just to be clear, the public leaderboard here is nonsense as it frequently is in most Kaggle contests. I enjoy overfitting them to show why that is the case. That said, there may be some advantage to leveraging january last values as I tried to do, but that remains to be seen. </p>
<p>There will very likely be fairly massive shakeup (shake down) here and I fully expect to be among the latter group.</p>
<p>For folks looking for a description of my model, I posted it here - <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/394810#2182222" target="_blank">https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/394810#2182222</a> </p>
<p>However, my experience was similar to most folks - simple linear models were best, perhaps informed a bit by economic/census features, and there wasn't much to write about. The CV studies I did showed that using last split CV was frequently superior (though more volatile for sure) to using more extensive validation.</p>
<p>New: I've uploaded the formal model submit file that was required to receive the prize distribution: <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/425000" target="_blank">https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/425000</a></p>
<p>Code here - <a href="https://www.kaggle.com/kaggleqrdl/first-place-code" target="_blank">https://www.kaggle.com/kaggleqrdl/first-place-code</a>, see below for an explanation.</p>
<p><strong>Acknowledgements</strong></p>
<p>Let me first acknowledge Kaggle, the Venture Forward folks, and GoDaddy. Not just for creating Kaggle itself, hosting the contest and providing the microbiz data - incredible feats of faith, truly - but also for being patient with my fixation on transparency. I am an egalitarian thru and thru, and firmly believe transparency is what gets us there.</p>
<p><strong>Introduction</strong></p>
<p>The contest was to predict microbusiness density 3,4,5 months lookahead for mar/apr/may 2023 per each of the 3135 US counties in the dataset. Microbusiness density here is roughly equal to the # of GoDaddy <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/374293" target="_blank">internet domains registered</a> / adult population in a county as measured by a 2 year lagging US census. </p>
<p>Eg: if a total of 10 GoDaddy domains were registered in <a href="https://en.wikipedia.org/wiki/De_Kalb,_Missouri" target="_blank">De Kalb, MO</a> with 200 adult population according to the 2021 census in 2023 February, than microbusiness density for that county would increase by 10/200 or 0.05 in that month.</p>
<p>We were given historical microbiz data for 2019 August -> 2022 December to train with, and a not-so-secret 'public LB' of data for January to validate against. Scores on the public LB were provided by Kaggle, and we were given 5 submissions per day.</p>
<p><strong>Method</strong><br>
To win this, I took a baseline prediction for the january public leaderboard based on overfitting it, and used linear regression to project into mar/apr/may</p>
<pre><code>, [, , ,] - month lookahead
, [, , ,] - month lookahead
, [, , , , ] - month lookahead
</code></pre>
<ol>
<li>l# here means lag # of months, shift is the actual value, just l#_ is pct_change</li>
<li>shiftf1_l1_active_logit is whether there was a change in active over previous month (l1_active != 1)</li>
<li>pct_college_2021 / pct_bb_2017 is from the census data the hosters shared</li>
<li>uemp / lf / ur are from the dataset I shared here - <a href="https://www.kaggle.com/datasets/kaggleqrdl/gd2022datasets" target="_blank">https://www.kaggle.com/datasets/kaggleqrdl/gd2022datasets</a></li>
</ol>
<p>I selected these features by cross validating on the last possible window (2,3,4 month respectively) without overlap. </p>
<p><strong>Insights</strong><br>
The key ideas that seemed to help:</p>
<ul>
<li>LB overfitting / probing. I did this by using the top public LB notebook plus focusing on the 10 or so counties that had recent significant volatility in the dataset. This was done because in non stationary time series data, the last value is your most powerful and compelling signal. It's worth noting that due to the <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/413974" target="_blank">dec22/jan23</a> snafu (we were given 60% incorrect data, as measured by SMAPE), this technique was severely impaired and my lead in the public LB went from ~0.2 to ~0.08 over the top 20. Overfitting the LB doesn't work very well when the LB has wrong data. <br>
More explanation here on this approach - <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/413109" target="_blank">https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/413109</a> I also explained these ideas early on in the contest <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/375244" target="_blank">here</a> and <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/378002" target="_blank">here</a>. The <a href="https://www.kaggle.com/kaggleqrdl/first-place-code" target="_blank">notebook</a> has code used for SMAPE root solving and probing techniques</li>
<li>LinearRegression - I tried practically every(*) other model and techniques, even dl/nn. LR consistently resulted in more reliable CV scores. Overfitting is always a concern with time series data and it's so easy to tune other models and convince yourself you found something superior.</li>
<li>Early stopping on greedy feature selection. This was done mostly on an intuition basis, but after running 1000s of experiments I developed a good feel for this I believe. I noticed overfitting occurring when I did more than 4 or 5 features, plus the decreased rate of improvement was another signal that overfitting had occurred. Certain features as well seemed to have more signal than others (eg, L10/11 employment, bb census) so I would keep going until they made it into the list but not much more.</li>
<li>Last window CV for feature selection. My hypothesis is that as a non stationary time series the relevant predictive features change and it's best to use the latest CV window (last few months of 2022). This played out in the results I saw over the experiments I did, but I will say std deviation on the error term was quite high, even if the mean was superior to longer CV periods. The risk was that so little CV time made it a bit of a gamble.</li>
<li>Use as much original training data as possible - Generalizing through data sufficiency was a reoccurring theme in this comp, and any technique that didn't appreciate it was degraded respectively. I used everything up to the lag window as per above. I didn't modify any of the data (beyond removing 3 problematic counties), even left the break in 2021 alone. I tried doing all sorts of things to clean up that data, but they just seemed to degrade results. </li>
<li>rounding based on active/population of course was a must. I found clipping, in the end, didn't help.</li>
</ul>
<p>*every regression model in sklearn, various arima libraries (a lot of time here, wasted I feel), hierarchical, xgb, catboost, lgbm, pytorch/dll. I tried both manually tuning the previous as well as various auto approaches like grid search/optuna. Lots of very exciting results, but eventually it occurred to me I was probably just overfitting.</p>
<p>It's worth observing that my lead against the #2 and #3 spots increased significantly from the public LB versus the private LB. I believe this was due to superior predictions for apr/may as my march results were somewhat lackluster. My lead over the top 20 spots also increased, though it is less clear how much of the public LB influenced their models.</p>
<p><strong>Ideas that didn't seem as important</strong></p>
<p>I also tried a lot of different datasets (including all the ones I shared publicly) up to and including google keyword trends for 'godaddy'. :) The above worked best when combined with early stopping. There would be sparks of good CV scores when using other features, but adding them frequently felt like overfitting. </p>
<p>I briefly looked into using zone files and whois databases, but these were not openly available so of course I didn't use them. </p>
<p>Crawling/Scraping would have in theory been public data, but I had committed to myself not to use any data that I didn't share openly, so I figured it wouldn't be worth the effort required. </p>
<p>Everything I used I shared in the <a href="https://www.kaggle.com/datasets/kaggleqrdl/gd2022datasets" target="_blank">dataset</a> I made publically available at the beginning of the comp.</p>
<p>I did a lot of initial work around per county models, work I eventually decided was wasted. There was barely enough data to validate the models and features above. There might be a way of segregate the counties, the question is - Would you have to segregate your training data as well? Would the increased complexity be worth what might potentially be only incremental improvements? Hard to say, especially since observing incremental improvements is mostly impossible when your CV scores are so volatile. </p>
<p><strong>Future directions</strong><br>
One thing I spent time looking at was correlation between the counties. There is an argument to be made I think that different counties may follow similar trends at potential lag times. There might be more to do here, but it would need to be done globally rather than individually, and your models would require appropriate data sufficiency. </p>
<p>Another feature I didn't plumb carefully enough was 1/2/3/etc annual renewal on GoDaddy domains, an idea I got by chatting with some domain resellers recently on a reseller domain community forum. I suspect they would provide a well of ideas around this that could be leveraged more.</p>
<p><strong>Final thoughts</strong></p>
<p>As I mentioned above, and others have mentioned, the data was non stationary except for some global linear growth coefficients. It's also been said that the smaller counties added a lot of noise, but I believe it was the right choice to try to see if we could do something there. There is a paucity of stats and analysis around more rural areas and emergent issues are hard to detect because of it.</p>
<p>Another way of looking at the data might be volatility instead of direction. The wild fluctuations in active domains could just be due to data errors but they could also be due to underlying social and economic factors. In the latter case, we need to consider: could the volatility be an opportunity, like the first sparks of a fire? Could these counties benefit from more targeted and opportune investment? If volatile counties have increased potential, what are the triggers for volatility? These are questions and experiments (signal + intervention) worth considering</p>
<p>If the VF folks would like to contact me (heh), feel free to reach out. As you may have noticed, I could talk about this stuff all day long with folks who are equally interested.</p>
<p>..</p>
<p>There was a bug in the team update that didn't let me change the LB pointer which I had originally pointed to the message below, so you're stuck with both. I originally pointed it here as I was more interested in what other folks did as I wasn't really that optimistic about my simplistic approach above. In retrospect, I probably should have trusted the process of elimination that I went through.</p>
<p>previous thread title: <strong>What is your mean active change over december for mar/apr/may?</strong></p>
<p>Edit - to make clear up front, you can share your results from your submission by just executing this code. It uses microbusiness density and not active, but that should be fine for comparison.</p>
<pre><code>dfc = pd.read_csv()
rt = pd.read_csv().set_index()
dfc[] = dfc[].apply( x:x[-:])
dfc[] = dfc[].apply( x:(x[:x.index()]))
dfc = dfc.reset_index().set_index()
dfc[] = dfc.apply( r:(r[] - rt.loc[, ])/rt.loc[, ], axis = )
display(dfc.groupby().mean()[])
</code></pre>
<p>….</p>
<p>It's going to be awhile before we get final results, and I think May results might play a large role in determining the eventual winners. While we wait, it might fun to share what we actually predicted. We could compare our actual results, which would be good and I've uploaded my two <a href="https://www.kaggle.com/datasets/kaggleqrdl/gd2022-subs" target="_blank">here</a> - but for those who don't want to and perhaps simpler might just be sharing mean % change over active.</p>
<p>Here's the code I used. It requires having accurate values for december in your dataframe and also have calculated 'active' as one of your columns. </p>
<p>If you don't want to use active, you can also share microbusiness density as well, but I found it less interesting because of the pop shift. There were some outliers in the pop shift that made it harder to ensure that nothing went awry, so I liked having active available. I've shared both below.</p>
<p>You can calculate cfips/first day with this code:</p>
<pre><code>dfc[] = dfc[].apply( x:x[-:])
dfc[] = dfc[].apply( x:(x[:x.index()]))
</code></pre>
<p>Calculate active_chg values with this code:</p>
<pre><code>dfc = dfc.reset_index().set_index()
dfc[] = dfc.apply( r:(r[] - dfc.loc[, ])/dfc.loc[, ], axis = )
dfc.groupby().mean()[]
</code></pre>
<p>This is my seasonal model </p>
<pre><code>first_day_of_month
--01 -
--01
-01-01
-02-01
-03-01
-04-01
-05-01
Name: active_chg, dtype: float64
</code></pre>
<p>This is my long trend</p>
<pre><code>first_day_of_month
--01 -
--01
-01-01
-02-01
-03-01
-04-01
-05-01
Name: active_chg, dtype: float64
</code></pre>
<p>Using mbd code if you didn't have an active column:</p>
<pre><code>dfc = dfc.reset_index().set_index()
dfc[] = dfc.apply( r:(r[] - dfc.loc[, ])/dfc.loc[, ], axis = )
dfc.groupby().mean()[]
</code></pre>
<p>Seasonal sub</p>
<pre><code>first_day_of_month
--01 -
--01
-01-01
-02-01
-03-01
-04-01
-05-01
Name: mbd_chg, dtype: float64
</code></pre>
<p>Long trend sub</p>
<pre><code>first_day_of_month
--01 -
--01
-01-01
-02-01
-03-01
-04-01
-05-01
Name: mbd_chg, dtype: float64
</code></pre>
<p>Note for february I just used the january values. Sharing january isn't really that helpful of course, I just do it for fun here.</p>
<p>I'll answer if you share your averages ;p <a href="https://www.kaggle.com/judith007" target="_blank">@judith007</a> </p>
<p>I pulled this from another contestants submission that they shared publicly. I won't give any names, but I found it interesting</p>
<pre><code>-03-01
-04-01
-05-01
</code></pre>
<p>Thanks Chen. I was hoping some folks might share their results, but so far everyone seems a bit shy. Ah well.</p>
<p>Thanks Luca, good luck to you as well.</p>
<p>Actually, I did provide some code above for just using microbusiness density. </p>
<p>Perhaps I should make this more clear.</p>
<p>If you run this, it should work. </p>
<pre><code>dfc = pd.read_csv()
dfc[] = dfc[].apply( x:x[-:])
dfc[] = dfc[].apply( x:(x[:x.index()]))
dfc = dfc.reset_index().set_index()
dfc[] = dfc.apply( r:(r[] - dfc.loc[, ])/dfc.loc[, ], axis = )
display(dfc.groupby().mean()[])
</code></pre>
<p>Yes, it does require having accurate december values. The pop shift problem should be OK as we'll all have it for comparison.</p>
<p>You can use this, I'll add it above</p>
<pre><code>rt = pd.read_csv().set_index()
dfc[] = dfc.apply( r:(r[] - rt.loc[, ])/rt.loc[, ], axis = )
</code></pre>
<p>Well, I let it run a little wild because of the layoffs in the tech sector. I sort of felt those folks might try to start up microbiz. Historically the tech sector has seen full employment, but lately less so, so I think using historical values we might be seeing some underestimations.</p>
<p>It's all guesses and fun though. I suspect we'll see a lot of new folk getting gold here</p>
<p><a href="https://www.kaggle.com/sireesh" target="_blank">@sireesh</a></p>
<p>Can you share them? Did you use fairly simple models?</p> |
GoDaddy - Microbusiness Density Forecasting | 11th Place Solution - Simplicity (Luck) Is All You Need | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Ty, I hope it would be a gold for me😂.</p>
<p>Do you mean using the data from <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/411428" target="_blank">here</a>?</p>
<p>I got </p>
<pre><code>. for single . for </code></pre>
<p>First, my thanks to Kagglers for very informative and helpful discussions and notebooks. Also, thank you to Kaggle and GoDaddy for hosting the competition.</p>
<p>My code is available at <a href="https://github.com/ywugwu/GoDaddy-MDF-Competition" target="_blank">github</a>, which is based on <a href="https://www.kaggle.com/code/vadimkamaev/microbusiness-density" target="_blank">VADIM KAMAEV's</a> public notebook. </p>
<p>In this competition, my idea is to keep improving my CV and PB score without letting my model grow too complex.</p>
<h1>Validation (CV)</h1>
<p>I used the last 5 month data for validation. The model with the best validation score is used as one of my final submissions.</p>
<h1>Model</h1>
<p>Same with the public notebook, I used a Catboost Regressor to stack a LightGBM, an XGBoost, and a CatBoost model. Tuning a lot hyperparameters.</p>
<h1>Feature Engineering</h1>
<p>I didn't do too much novel feature engineering, only used techniques from public notebooks. </p>
<p>But I change the hyperparameters a lot.</p>
<h1>Blending Submissions</h1>
<p>I used different hyperparameters of the model and different features (i.e., with different diff, max, mean, etc. settings) to conduct a large number of submissions. I select the best 4 (or maybe 3) submissions and use a weighted average to create a blended submission. The best (according to the public leaderboard) blended result is selected as one of my final submission. In the end, the private leaderboard score of blended submission is slightly better than the best CV model.</p>
<p>thanks for your reminder, I added an extra <code>.</code> at the end of my URL 😭. Now, It should work. </p> |
GoDaddy - Microbusiness Density Forecasting | 2nd Place solution: The Godaddy Microbusiness Data Cleaning Challenge | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>You probably would have gotten a similar result based on your technique. </p>
<p>For the cross validation, I know in some public notebooks there was an explicit violation of proper CV technique since the smoothing was done before the cross validation. I think to properly setup your environment given the challenge and the data quality, all data cleaning, etc should be a part of the model itself and all cross validation should be done in a walk forward mode since it is a time series challenge. </p>
<p>For example, the GRU models used with Group K fold would in this case use the the group CV for early stopping and validation of the training phase, but to test the overall model one would need to use the walk forward method.</p>
<p>Not sure of your setup, so this may not affect you</p>
<p>For the Jan predictions, not sure I can answer that until the end of the competition. Much of that is just a hope that the interaction of those predictions with my model will not cause some bias that I could not detect.</p>
<p>Given my CV setup, a last value model gave these results on the original training data:<br>
Train up to and including data from 2022-01-01 and evaluate forecasts from 2022-04-01 to 2022-06-01 = 3.1956774734784967<br>
Train up to and including data from 2022-02-01 and evaluate forecasts from 2022-05-01 to 2022-07-01 = 3.4152913611520037<br>
Train up to and including data from 2022-03-01 and evaluate forecasts from 2022-06-01 to 2022-08-01 = 3.3317878979931765<br>
Train up to and including data from 2022-04-01 and evaluate forecasts from 2022-07-01 to 2022-09-01 = 3.3842283789667764<br>
Train up to and including data from 2022-05-01 and evaluate forecasts from 2022-08-01 to 2022-10-01 = 3.7841915766675602<br>
Average SMAPE = 3.4222353376516024</p>
<p>And the final model I used:<br>
Train up to and including data from 2022-01-01 and evaluate forecasts from 2022-04-01 to 2022-06-01 = 2.962060956397758<br>
Train up to and including data from 2022-02-01 and evaluate forecasts from 2022-05-01 to 2022-07-01 = 3.097867393456829<br>
Train up to and including data from 2022-03-01 and evaluate forecasts from 2022-06-01 to 2022-08-01 = 3.0168450673149243<br>
Train up to and including data from 2022-04-01 and evaluate forecasts from 2022-07-01 to 2022-09-01 = 2.9881429431194393<br>
Train up to and including data from 2022-05-01 and evaluate forecasts from 2022-08-01 to 2022-10-01 = 3.3630555199321344<br>
Average SMAPE = 3.085594376044217</p>
<p>Interesting problem, and it was also interesting to see the solutions came up with. I'm pretty new to these competitions. The biggest uncertainty to me is how much probing of the hidden data is allowed, especially in a case like this where it matters a lot for time series prediction.</p>
<p>I also though SMAPE was a weird choice of metric that didn't make sense in a business sense. A change in a small county would have a large influence in SMAPE, where if you are trying to capture revenue streams, wouldn't you care a lot more about a change in the number of active forecasts in Los Angeles? I can only imagine this would be useful for allocation of advertising dollars.</p>
<p>The code: <a href="https://www.kaggle.com/code/danielphalen/godaddy-microbusiness-final/notebook?scriptVersionId=133942554" target="_blank">Godaddy Microbusiness Final</a></p>
<h2>The biggest issue - Data quality</h2>
<p>As has been pointed out by many people, SMAPE is a relative metric. With the kind of forecast values we are looking at (~1.2-1.5 for 1 month, ~3.2 for months 3-5 together), we can look at the contribution of an individual CFIPS. </p>
<p>$$\Delta_{SMAPE,i} = \frac{200}{n_{counties}} \frac{|F_i - A_i|}{F_i+A_i}$$</p>
<p>Which, in the case of something going from zero to non-zero can be ~0.0638 per month difference. At the same time, a prediction for most of these models seems to be on the order of 0.5% change per month, which is far below the smallest change in active entries for many 25% of the counties. </p>
<p>Second, there are many CFIPS where the data is terrible. The hosts acknowledged that they had a methodology change in Jan 2021, leading to a number of jumps, and I suspect there was another change after the first month. </p>
<p>The one which always bothered me was CFIPS 56033, Sheridan Co, WY, where there are 2.36 microbusinesses/working age person. I can only guess there is some bug where if there is a misclassification they dump it in that CFIPS. I also wondered if there was some fraud happening during COVID times as people chased PPP loans given the large jumps. However, many of these issues would eventually revert, like the below:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5552115%2Fc85777fd4f981dee2765e2b78b7f1236%2Fcfips48155.png?generation=1678978908088571&alt=media" alt=""></p>
<p>So the question I think that make or breaks this, if we identify a large jump, will it revert? In this I believe we are helped by the gap between December and the first forecast month, March. I also hope GoDaddy gets better in their data collection procedures, which would help. In then end, if they want to use this in business, it would probably not be that useful to have a large machine learning error correction model for data collection issues.</p>
<p>My solution is a mix of public leaderboard probing for individual CFIPS changes, reversion for outlier CFIPS, and a forecast of the smooth changes. </p>
<h3>Public leaderboard - still very useful information</h3>
<p>Given the equation above and as <a href="https://www.kaggle.com/petersorenson360" target="_blank">@petersorenson360</a> suggested, and that the leaderboard was active to 4 decimal places, you are sensitive to changes of less than 1% in the value an individual value. Given you had about 20 days from revealed test to final submission deadline, you could probe about 100 CFIPS for final values. It was actually easier if you made the value worse since the equation above would allow you to work out the exact number of active entries. </p>
<p>Many large jumps would the revert, which we tried to work out how long that might take. This will probably be the difference in the end of who wins and loses, and I think the couple month gap between the test and private data will help ensure they revert. This was by far the top influence.</p>
<h3>Continuous Model</h3>
<p>After seeing GiBa's <a href="https://www.kaggle.com/titericz" target="_blank">@titericz</a> notebook, his data cleaning method reminded me of something used in futures algorithmic trading, called a <code>continuous contract</code>. Basically, you need to take a discontinuous series of prices and make it smooth. So for what I will call the continuous forecast, I used a data cleaning method where I looked for large jumps in the number of active entries, then did a shift to smooth them out. So the month where there was a large active jump became zero active jump. This smoothing method gave the best CV score of the number that I tried.</p>
<p>I then setup the CV environment. For the model used XGBoost, added extra indicators, and prevented peeking in the future:</p>
<ul>
<li>lagged density changes and lagged active values</li>
<li>pct_bb, pct_college, pct_it, pct_foreign_born, median_hh_inc of the last year (Many public books used an implicit forward bias in their features by looking at 2021 census data when training on 2019 data)</li>
<li>Labor Force and Labor force participation for the county</li>
<li>10 year average pct population change for the county</li>
<li>latitude and longitude</li>
<li>engagement, participation, and MAI_composite from the Godaddy website.</li>
<li>The difference between the microbusiness density and the average of the neighboring counties, weighted by population.</li>
</ul>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5552115%2Ff1ba9755aeb2b45525fd98359dbf9cd2%2FFeatureImportances_1.png?generation=1687036241940575&alt=media" alt=""></p>
<p>I found a population cut of about 5,000 was helpful. Rounding the model to an integer number of active helped a bit. A lot of these external indicators proved more helpful for the longer term forecasts, where there is some reversion to an average.</p>
<p>Other notes:</p>
<ul>
<li>I actually found training on the 1 month forward change then feeding that prediction back into the model and recalculating all indicators gave the best CV, as opposed to directly forecasting the 3 month ahead forecast. It turned out to be less biased.</li>
<li>The <code>scale</code> variable used seemed to work in forecasting the public leaderboard, but did terribly in my CV environment.</li>
<li>Again, noting that the last value is pretty good and I was using a roll forward model, I used the tuned public models to patch in a January forecast as an estimate for the ground truth, then rolled forward the XGBoost model from that.</li>
</ul> |
GoDaddy - Microbusiness Density Forecasting | 35th Place Solution - GRU+XGB | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Goal of this competition was to predict monthly <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/374293" target="_blank">domain registrations of small businesses</a> divided by the active population for all counties in the US. The biggest difference to other timeseries competitions is in my opinion that the public leaderboard tracked the score of the one month forecast (January) while our final score would be determined on 3-5 months in the future (March, April, May). My expectation for this competition was to deal with various macroeconomic explanatory variables and maybe even include some capital markets data. As it turned out this was not the case😄.</p>
<h3>Things that did not work</h3>
<ul>
<li>I spent more time than I'm willing to admit on scrolling through files from statsamerica (<a href="http://www.statsamerica.org/downloads" target="_blank">www.statsamerica.org/downloads</a>) trying to find anything helpful to enhance the data we had at hand. Unfortunately I can't present any evidence for it's usefulness in this context. Anyway they have cool stuff (<a href="https://www.statsamerica.org/innovation" target="_blank">https://www.statsamerica.org/innovation</a>) over there.</li>
<li>Capital markets indicators also had little effect. The decision to register a domain is surprisingly not driven by the VIX or FOMC dots (or more precise it does not help on county level forecasting).</li>
</ul>
<h3>Data Quality and Preprocessing</h3>
<p>Instead, outlier detection was the name of the game. I didn't probe the leaderboard but nevertheless spent much time comparing small counties and their erratic timeseries. Additionally, we had to deal with a <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/375715" target="_blank">structural change</a> in the data in January 2021 and the <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/389215" target="_blank">underlying population numbers</a> were also shifting. </p>
<p>Therefore the target variable was adjusted for the latest census data and I removed suspect jumps for all counties in this month if they exceeded a threshold of +-7%:</p>
<pre><code> o tqdm(raw.cfips.unique()):
indices = (raw[]==o)
tmp = raw.loc[indices].copy().reset_index(drop=)
var = tmp.microbusiness_density.values.copy()
var_pct = tmp.microbusiness_density.pct_change().clip(-,)
j (, , -):
j== (var_pct[j]== - var_pct[j]== ):
var[j-] = var[j]
:
var[j-] = var[j]/(+var_pct[j])
raw.loc[indices, ] = var
</code></pre>
<p>Afterwards the timeseries was further denoised with an autoencoder:</p>
<pre><code> ():
i = tf.keras.Input(shape=(,))
encoded = tf.keras.layers.BatchNormalization()(i)
encoded = tf.keras.layers.GaussianNoise(noise)(encoded)
encoded = tf.keras.layers.Dense(,activation=)(encoded)
decoded = tf.keras.layers.Dropout()(encoded)
decoded = tf.keras.layers.Dense()(decoded)
x = tf.keras.layers.Dense(,activation=)(decoded)
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.Dropout()(x)
x = tf.keras.layers.Dense(,activation=)(x)
encoder = tf.keras.Model(inputs=i,outputs=x)
loss = tf.keras.losses.MeanSquaredError()
encoder.(optimizer=Adam(),loss=loss)
encoder
</code></pre>
<p>I'm unsure if this could add any kind of leakage as it was applied before/outside of the CV fold structure. But it stabilized my CVs and had no negative impact on the public leaderboard score. Anyway I kept using it only for the GRU model and trained XGB on the 'raw' data.</p>
<h3>Models and Target</h3>
<p>Only counties with more than 150 microbusinesses were considered as input for the model. For counties below this threshold the last value was used.<br>
Building on top <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/381038#2114357" target="_blank">Chris proposal</a> I used GRU with 24 months sequence of np.log1p(microbusiness density) input combining 3 folds (GroupKFold grouped by date) and forecasting 1, 3, 4, 5 months into the future.<br>
As a second model I used XGB derived from what <a href="https://www.kaggle.com/code/titericz/better-xgb-baseline" target="_blank">GIBA shared</a>, defining the 1, 3, 4, 5 months growth difference as a target. Most of the county level features were included here but I think they added little explanatory value. For postprocessing I clipped the XGB predictions of the percentage changes with the corresponding 10% and 90% quantile values observed after preprocessing. Both models are weighted with 50% in the final submission.</p>
<h3>Second Submission</h3>
<p>This was a simple linear model inspired by the success of <a href="https://www.kaggle.com/code/vitalykudelya/21-lines-of-code" target="_blank">21 lines of code</a>. It calculated the average monthly growth per county on the 21 months after the structural break in January 2021. The mean was clipped at -0.5% and +1% and for counties with less then 150 active domains this value was scaled by 0.3 (all of this was expert judgement based on very crude statistics, average growth, 5%,25%,75%,95% quantiles of growth). For counties with stale growth in November and December the last value was forecasted perpetually. This scored 4.0731 which would have been place 175 (still a silver medal with 10% of the effort). 🙀</p> |
GoDaddy - Microbusiness Density Forecasting | 3rd Place - Predict Multipliers with GRU | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><blockquote>
<p>How is the 1.0045 value obtained through probing used? When predicting 5 values, is it fixed as the first ratio value?</p>
</blockquote>
<p>After the GRU makes prediction for January, we compute the ratio of "average January prediction" divided by "average December prediction" for large counties. The result is <code>1.0032</code>. This is not the optimal ratio. So we multiply every January prediction for large counties by <code>1.0012</code>. Afterward, the the ratio of "average January prediction" divided by "average December prediction" is <code>1.0045</code> and our public LB and private LB are boosted.</p>
<p>Regarding the small counties, each begins with multiplier of <code>1</code> which means that each small county prediction uses the December 2022 value. We then try different multipliers for different small counties and keep ones that improve LB. Basically we are finding what the small counties ground truth is for January 2023. Then our final submission uses the January values for small counties instead of December values for small counties. This boosts public and private LB.</p>
<p>Both post processes combined improve CV and LB by about <code>+0.05</code></p>
<p>Thank you Kaggle and GoDaddy for an exciting forecasting competition!</p>
<h1>Predict Multipliers with TensorFlow GRU</h1>
<p>Our forecasting models need to predict 3135 county microbusiness density predictions per future month. The public LB is one future month and the private LB is three future months (with 2 month gap between train and test).</p>
<p>From Kaggle's M5 competition <a href="https://www.kaggle.com/competitions/m5-forecasting-accuracy/discussion/163621" target="_blank">here</a> we learned that predicting multipliers (between the test time period and train time period) was most important. For example in M5, we could take an average public notebook and multiply all predictions by <code>0.95</code> and win Gold medal !! Similarly in Kaggle's GoDaddy competition, a simple last value baseline multiplied by the correct January/December multiplier of <code>1.0045</code> as shown in Vitaly's notebook <a href="https://www.kaggle.com/code/vitalykudelya/21-lines-of-code" target="_blank">here</a> achieved Gold medal public LB for many months!</p>
<p>To predict multipliers, we convert train data into multipliers and then train a TensorFlow GRU. This simple model achieves 15th place Gold. Then if we post process the multipliers based on ratios learned from LB probing, we boost our solution to 3rd place Gold !!</p>
<h1>Original Train Data</h1>
<p>Kaggle gave us 41 historical months of data for each of 3135 USA counties. </p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/Jun-2023/data1.png" alt=""></p>
<h1>Step 1 - Adjust Train Data</h1>
<p>The definition of microbusiness density is <code>micro businesses per 100 people over age 18</code>. The value of microbusiness density changes when county population changes. So the first step is to convert all microbusiness density to use the same 2021 census. We use the formula</p>
<pre><code> = microbusiness_density * (population / population_year_2021)
</code></pre>
<h1>Step 2 - Create 56,000 Time Series!</h1>
<p>For each county, we create 18 time series. We use 13 consecutive months to train our GRU and predict the next 5 months. (Pictured below is only 3 time series per county for illustration purposes). Afterward, we have 56,000 time series to train with!</p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/Jun-2023/data2.png" alt=""></p>
<h1>Step 3 - Use Only Top 90% Largest Counties</h1>
<p>We notice that the smallest 10% counties have nearly the same microbusiness density from month to month, so we only train our GRU using the largest 90% counties. During inference, we will use the last known value as prediction for small counties.</p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/Mar-2023/growth.png" alt=""></p>
<h1>Step 4 - Convert to Multipliers</h1>
<p>Each county has 13 months of train and 5 months of valid. We will convert the raw micro business data into ratios by replacing each value with the ratio of current month divided by previous month. Afterward we will have 12 months of train ratios and 5 months of valid ratios</p>
<pre><code>
k in range():
[:,k+] = old_data[:,k+] / old_data[:,k]
</code></pre>
<h1>Step 5 - Train GRU with GroupKFold</h1>
<p>When creating KFold we need to use GroupKFold and keep all time series for each county (from the possible 18 time series per each county) within the same fold. Otherwise CV score will be inaccurate and we cannot optimize our models hyperparameters correctly. Below is our TensorFlow GRU model which takes an input of 12 ratios and predicts 5 ratios:</p>
<pre><code>def build_model():
inp = tf.keras.Input(shape=(12,1)) # INPUT SHAPE IS 12
x = tf.keras.layers.GRU(=8, =)(inp)
x = tf.keras.layers.GRU(=8, =)(x)
x = tf.keras.layers.GRU(=8, =)(x)
x = tf.keras.layers.Dense(5,=)(x) # OUTPUT SHAPE IS 5
model = tf.keras.Model(=inp, =x)
opt = tf.keras.optimizers.Adam(=1e-4)
loss = tf.keras.losses.MeanSquaredError()
model.compile(=loss, optimizer = opt)
return model
</code></pre>
<h1>Step 6 - Infer and Post Process</h1>
<p>We predict each county individually. To make predictions for January 2023. We begin with the last known value (of the county we are predicting) from December 2022 and multiply by the first ratio predicted by our model. To predict Feb 2023, we take our Jan 2023 prediction and multiply by the second ratio predicted by our model. To predict Mar 2023, we multiply Feb 2023 by third ratio. To predict Apr 2023, we multiply by fourth ratio. And finally to predict May 2023, we multiply by fifth ratio.</p>
<p>We can improve our predictions by modifying the first ratio (which is the ratio of January 2023 divided by December 2022) by information from probing the public LB. Probing informs us that the best January/December average ratio for the largest 90% counties is <code>1.0045</code>. Similarly, we can improve our predictions for small counties by probing the public LB to find ratios for different sized small counties.</p>
<p>Post process boosts our GRU solution from 12th place Gold to 3rd place Gold !!</p>
<h1>GRU Solution Code Published</h1>
<p>Full solution code with preprocess, train, and infer is published <a href="https://www.kaggle.com/code/cdeotte/gru-model-3rd-place-gold" target="_blank">here</a>. </p>
<h1>More Solution Models</h1>
<p>My final two submissions were</p>
<ul>
<li>GRU with PP - 3rd place</li>
<li>Linear Model with PP - 10th place</li>
</ul>
<p>More information about my linear model is <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/395098" target="_blank">here</a>. Enjoy!</p>
<p>No, my previous post is <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/395098" target="_blank">here</a></p>
<p>Congratulations <a href="https://www.kaggle.com/kaggleqrdl" target="_blank">@kaggleqrdl</a> winning first place!</p>
<p>The competition metric is SMAPE which is about ratios of error divided by mean of prediction and ground truth. When training a model, using different losses can have different effects on model accuracy with relation to competition metric. Another way to affect model accuracy without changing the loss function is to transform the targets. Using MSE loss with ratios does a better job optimizing SMAPE than trying to predict the raw microbusiness values with another loss. Also transforming targets make more targets similar. For example when using raw microbusiness values, maybe the values do not repeat themselves often, but when converting everything into ratios, the ratios do repeat themselves often which reinforce the model's learning.</p> |
GoDaddy - Microbusiness Density Forecasting | 44th Place Solution - Simple LGBM | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you for the competition on a very interesting topic. It was a time-series forecasting problem that predicts the true future, and was a fun theme to solve. I understood that the United States is a very large and diverse country.</p>
<p>This is a simple LightGBM, 44th Place Solution.</p>
<h3>Solution Overview</h3>
<ul>
<li><p>Only LightGBM with 32 features </p></li>
<li><p>Multiplier Prediction<br>
I chose target as the multiplier between the previous month's data and the month to be predicted.</p></li>
<li><p>Target smoothing<br>
Because there were so many outliers in the data, I smoothed the target by taking the medians of the three cases before and after the target.</p></li>
<li><p>Model to forecast 1-6 months later<br>
I created several models to forecast 1-6 months later separately.</p></li>
<li><p>Average of 3 months<br>
Average the multipliers for 3 months, including the months before and after the month of forecast. This is more accurate.</p></li>
<li><p>Conversion of population from 2020 to 2021</p></li>
<li><p>Round(0) since it is a discrete value</p></li>
</ul>
<h3>My Notebook</h3>
<p>I have published my notebook below.<br>
<a href="https://www.kaggle.com/code/thajime/godaady-44th-solution-lgbm" target="_blank">https://www.kaggle.com/code/thajime/godaady-44th-solution-lgbm</a></p> |
GoDaddy - Microbusiness Density Forecasting | 62th Place Solution - Last Value and Rule-based Multiplier | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I selected constants that were minimizing my validation score so I didn't think I was overfitting at any time. </p>
<h2>Validation</h2>
<p>Validation is really important for problems like this. I baffled by lots of people validating on last month without any gap. Replicating test set split was essential for the validation scheme so I used 8 folds of 2 months gap and 3 months validation with expanding window over the entire dataset. I also added 3 additional folds with their training period ending on December for simulating new year transitions. I had 11 folds but I didn't necessarily use all of them at the same time.</p>
<h2>Models</h2>
<p>I tried some models but none of them improved my validation score so I had to use last value baseline. These are the models and techniques I tried:</p>
<ul>
<li>Linear regression, LightGBM and XGBoost with raw and external pivoted features from GoDaddy Venture Forward Data Hub</li>
<li>Linear regression with normalized month and target for each county</li>
<li>ARIMA, SARIMAX and other auto-regressive model variations for each county</li>
<li>Directly optimizing a multiplier for last value using bayesian optimization</li>
<li>Last value and a ruled-based multiplier</li>
</ul>
<h2>Last Value + Rule-based Multiplier</h2>
<p>As everyone knows, this was a quite strong baseline. I wasn't able to beat this with other models so I decided to improve it by making data-driven decisions.</p>
<p>First thing I did was adjusting last values to new year which is mentioned <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/389215" target="_blank">here</a> by <a href="https://www.kaggle.com/cdeotte" target="_blank">@cdeotte</a>. I got similar validation score boost when I tested this adjustment on my last three folds that were simulating new year transitions.</p>
<p>The other thing I did was checking last 5 target values of each county:</p>
<ul>
<li>If target increased every time: Last value is multiplied with 1.010 for March, 1.015 for April and 1.015 May</li>
<li>If target decreased every time: Last value is multiplied with 0.998 for March, 0.994 for April and 0.990 May</li>
<li>If target was making sideways (else case): Last value is multiplied with 1.010 for March, April and May</li>
</ul>
<p>Lots of time passed since submissions are closed so I don't remember my exact validation scores but I remember that I got a significant boost with this approach. I didn't use Kaggle notebooks on this competition either. I was generating submissions on local and uploading them. This repository is the only thing I can share…<br>
<a href="https://github.com/gunesevitan/godaddy-microbusiness-density-forecasting/" target="_blank">https://github.com/gunesevitan/godaddy-microbusiness-density-forecasting/</a></p>
<p>and this is the script that generates 67th place predictions.<br>
<a href="https://github.com/gunesevitan/godaddy-microbusiness-density-forecasting/blob/main/src/county_models/last_value.py" target="_blank">https://github.com/gunesevitan/godaddy-microbusiness-density-forecasting/blob/main/src/county_models/last_value.py</a></p> |
GoDaddy - Microbusiness Density Forecasting | 6th Place Solution - Lightgbm with Target flattened | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations winning the 1st place!</p>
<p>This formula is construct by testing without theoretical basis. Here is the procedure:</p>
<ol>
<li>get the initial target:<br>
<code>raw['target'] = raw.groupby('cfips')['microbusiness_density'].shift(-1)</code><br>
<code>raw['target'] = raw['target']/raw['microbusiness_density'] - 1</code></li>
<li>plot the target distribution for different active base.The distribution of target variables changes with the change of active base. The lower the active base is, the higher the absolute value of the target is.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F425081%2F2d5b2ff154d7bcf3b275d00c216cc819%2FWechatIMG1609.png?generation=1687007781010306&alt=media" alt=""><br>
3.Assume that after transforming all active base into same target distribution,the distribution will be flattened like a straight line.Then find a suitable transform formula just like this:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F425081%2F6a3bada85896f94a78b9c9d3eb36b525%2FWechatIMG1608.png?generation=1687007922643410&alt=media" alt=""></li>
</ol>
<p>Great Thanks to kaggle and Godaddy to hold this competition. Congratulations to all the winners. And many thanks go to people who created some mazing public notebooks.<br>
Here is my Solution:</p>
<h1>Validation</h1>
<ul>
<li>Last 12 month data for validation. </li>
<li>To evaluate any solution is validate, I additionally compute the number of improve months of the 12 valid month instead of simple average cv improve.Because some month have abnormal high/low raising rate:<code>mbd(curr_month+1)/mbd(curr_month)-1</code>,average cv may lead to overfit</li>
</ul>
<h1>Outlier smooth</h1>
<ul>
<li>Mean smoothing for 2022-06->2022-08 to handle the general sharp rise-fall phenomenon
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F425081%2F97e293203e0ddc5a997612331e424658%2F2023-06-17%2017.54.47.png?generation=1686995741884356&alt=media" alt=""><ul>
<li>There are also other data points have the phenomenon like "origin->Sharp rise-> Sharp fall->origin".But I haven't found the best way to deal with them yet.</li></ul></li>
<li>Basic constant smoothing by fraction from giba</li>
<li>Stable blacklist for those nearly unchanged cfips<ul>
<li>[28055, 13101, 13265, 31009, 31115, 31149, 38047, 38087, 48033, 48301]</li></ul></li>
</ul>
<h1>features:</h1>
<ul>
<li>Action diff, Target shift, Target diff</li>
<li>Target diff window <ul>
<li>Sum</li>
<li>Std</li></ul></li>
<li>Target window<ul>
<li>Sum</li>
<li>Quantile 0.2</li>
<li>Quantile 0.8</li>
<li>Lowwer bound:<ul>
<li>only have value when sign(Quantile 0.2)=sign(Quantile 0.8),0 for other situations</li>
<li>Quantile 0.8 for negative value</li>
<li>Quantile 0.2 for positive value</li></ul></li></ul></li>
<li>State cluster</li>
</ul>
<h1>Enhance modeling framework</h1>
<p>construct the Enhance model frame, input 1)feature and 2) n_cross: number of future month to predict, output the raising rate of mbd in future n_cross month. In this way we can directly predict the public/private mbd by changing n_cross from 1-5<br>
Detail structure:</p>
<ul>
<li>Enhance modeling frame features=features+n_corss</li>
<li>n_corss=num of month to predict future mbd</li>
<li>output target:[mbd(curr_month+n_corss)/mbd(curr_month)]**(1/n_corss)-1</li>
<li>Model:Xgboost </li>
</ul>
<h1>Target_flatten:Train with flattened target, and do reverse transform in prediction</h1>
<ul>
<li>The distribution of target variables changes with the change of active base. The lower the active base is, the higher the absolute value of the target is.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F425081%2Fdac497d7f6b9266fcd2e81242c29cf3c%2FWechatIMG1604.jpeg?generation=1686995149378846&alt=media" alt=""></li>
<li>Do a simulate to transform all active base into same target distribution. We assume the distribution will be flatttened after the transformation, in this way we can construct the transform formula by testing:<ul>
<li><code>coef=(1/(0.007*(active_series/10+105))+1)</code></li>
<li><code>target_flatten=target_series/coef</code></li></ul></li>
<li>Train with flattened target, and do reverse transform in prediction</li>
</ul>
<h1>Post process</h1>
<ul>
<li>I noticed that the trend of public leaderboard month is abnormal higher than normal months.This phenomenon also happends on other month like 2022-07, In my opnion, such whole month trend is unpredictable, our model should not overfit it.</li>
<li>Considering that the mbd for the public month is the basis for the subsequent private month, I post-processed the forecast results like:<br>
<code>prediction=prediction*(1+0.001)</code></li>
</ul> |
GoDaddy - Microbusiness Density Forecasting | 99th Place Solution - LightGBM and Rule-based Multiplier | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Basic strategy</h1>
<h3>How to get 5 months predictions</h3>
<p>In this competition, we were required to make predictions for up to 5 months ahead. I decided to obtain 5 months of predictions by repeating the 1 month forecast five times. This approach made it easier to take advantage of the excellent predictions for January 2023 from the Public Notebook.</p>
<h3>Validation</h3>
<p>For validation, I used 5 months of data from August 2023 to December 2023. For the 1-month ahead forecast, I used data up to November 2023 for the December 2023 prediction and data up to July 2023 for the August 2023 prediction. For the 5-month ahead forecast, I used data up to July 2023 for the December 2023 prediction and data up to March 2023 for the August 2023 prediction. Using this method, I created predictions for each month as 1-month ahead to 5-months ahead predictions. I adjusted the models and features based on this validation score.</p>
<h3>External data and Population Adjustment</h3>
<p>Based on <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/389215" target="_blank">Chris Deotte's explanation</a>, I adjusted the microbusiness density values based on population, ensuring that the denominator of microbusiness density was the population of the same year throughout the data. As external data, I incorporated the census data given by the host and the data of cfips locations into the model. I did not utilize any other external data because they didn't improve my validation scores.</p>
<h1>Models</h1>
<h3>Overview</h3>
<p>The overview of the prediction model is as follows. I used the model of <a href="https://www.kaggle.com/code/titericz/better-xgb-baseline" target="_blank">Giba's excellent notebook</a> as the starting model. Then I made rule-based adjustments to get the prediction values. I got hints for rule-based adjustments from Chris Deotte's notebook (<a href="https://www.kaggle.com/code/cdeotte/linear-regression-baseline-lb-1-092" target="_blank">here</a> and <a href="https://www.kaggle.com/code/cdeotte/seasonal-model-with-validation-lb-1-091" target="_blank">here</a>).</p>
<h3>Base model</h3>
<p>For the base model, I mostly adopted the preprocessing (including outlier corrections), feature engineering and target transformation from Giba's notebook. I used a LightGBM model with a small number of trees (n_estimators=30) as the model since complex models tended to overfit quickly according to the validation results. The remaining settings were determined through experiments based on the validation score. </p>
<ul>
<li>I didn't use a blacklist. </li>
<li>I tried several settings for outlier correction and the number of lag and window variables</li>
<li>I excluded cfips with less than 140 active values from models.</li>
</ul>
<p>This model gives an upward trend for most cfips. As pointed out in various notebooks, microbusiness density showed a global upward trend, so I believe this model roughly captures that trend.</p>
<h3>Adhoc rules</h3>
<p>I implemented two types of rule-based adjustments: trend-based and seasonal effects. These adjustments exclude cfips with low active values. For trend-based adjustments, I prepared rules such as "For cfips that have increased 1+x times in the last n months (or n-1 months), the average of the growth rate is multiplied by 1-y to obtain the new growth rate." Since applying the same rule repeatedly up to 5 months ahead often leads to overfitting, my adjustments become more conservative for farther predictions. For example, when creating the May 2023 prediction from the April 2023 prediction, trend-based adjustments are hardly applied.</p>
<p>Regarding seasonal effects, I assumed effects based on months and prepared rules such as "For cfips that have increased by 1+x times or more compared to the previous month every time in the same month in the past, the average of the growth rate is multiplied by 1-y to obtain the new growth rate." It might be difficult to obtain conclusive evidence of the monthly effects based on the training data alone, but considering that what we want to predict is the economic index and validation scores were improved by this rule , I assumed their existence. </p>
<p>In these rule-based adjustments, I implemented both upward and downward adjustments. However, considering the property of SMAPE, where downward deviations are less desirable than upward deviations, I made aggressive adjustments in the upward direction and conservative adjustments in the downward direction. In case of overlapping adjustments, I took the average. The threshold and detailed settings of the rules were determined through experiments based on the validation score.</p>
<h1>Getting predictions and creating submission files</h1>
<p>To get predictions, I used the best score from the Public Notebook as the starting point for the January 2023 prediction and incorporated the results of Public LB probing. The Public LB probing consists in the same rule-based approach described above. I applied multiple adjustments for both long-term and short-term trends in addition to seasonal effects. Using the obtained January 2023 prediction as the starting point, I made predictions up to May 2023 by repeating the 1-month ahead forecast. I also applied adjustments shown in <a href="https://www.kaggle.com/code/vitalykudelya/use-discrete-nature-of-microbusiness-density" target="_blank">Vitaly Kudelya's notebook</a> to the obtained predictions.<br>
We can submit two files as final submission. For one submission, I submitted the prediction where rule-based adjustments were aggressive, and for the other submission I submitted the prediction where rule-based adjustments were modest. As a result, the former one was better than the latter one, which held also in validation scores.</p>
<h1>Acknowledgements</h1>
<p>Most of the basic ideas were fairly simple and derived from public notebooks. Setting up appropriate validations was cumbersome, but by attempting the combinations of these ideas based on the validation scores, I was able to achieve this rank. Thanks to Kagglers for many thoughtful and helpful notebooks and discussions. In competitions like this one, where the Public LB and Private LB data differ significantly, it can be difficult to determine what to trust, but preparing reliable validation is crucial above all else. My code is available at <a href="https://github.com/KazuakiTokunaga/kaggle-godaddy" target="_blank">github</a>. </p> |
GoDaddy - Microbusiness Density Forecasting | ??? Place Solution - Clustering County Stats | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I would train on data up until the time of prediction so that I was not leaking "future" data. For example, the first validation window looks like the following. I have external features up until 2022-07-01, but am predicting the change in microbusiness density from 2022-04-01 to 2022-09-01.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5570735%2F419b7607949a90a2e2c4d48fe5837cdc%2FUntitled%20Diagram%20(4).jpg?generation=1678923210797113&alt=media" alt="Drawing"></p>
<p>For the 2-step model I only validated on the final 4 months. The prediction windows were: </p>
<p>2022-07-01 -> 2022-09-01 (last known mbd: 2022-04-01)<br>
2022-08-01 -> 2022-10-01 (last known mbd: 2022-05-01)<br>
2022-09-01 -> 2022-11-01 (last known mbd: 2022-06-01)<br>
2022-10-01 -> 2022-12-01 (last known mbd: 2022-07-01)</p>
<p>First of all, thank you to GoDaddy and <a href="https://www.kaggle.com/kellenjgracey" target="_blank">@kellenjgracey</a> for hosting this awesome competition. Also, thank you to everyone who shared ideas in the discussion forums.</p>
<p>The main idea of my solution was to fit 3x6x3 XGB models. I will try my best to explain this below.</p>
<p><strong>Clustering</strong></p>
<p>The idea was as follows. </p>
<ol>
<li>Order the data</li>
<li>Split the data into 3 equal size groups</li>
<li>Fit 3 XGB models (9 total) to each group (0-step, 1-step, and 2–step ahead)</li>
<li>For each cfips, if predicting the last value outperformed XGB for all step-ahead models then assign that cfips to a 4th cluster.</li>
</ol>
<p>I performed the steps above with 6 features</p>
<ul>
<li># people age 30-34</li>
<li># people w/ a tablet or other portable wireless computer</li>
<li>PCT of population w/ two or more races</li>
<li>County GDP</li>
<li>PCT of businesses w/ between 10-19 employees</li>
<li>Price reduction in homes over the past 12 months</li>
</ul>
<p>And the size of each cluster was as follows (the 4th value is the last-value cluster).</p>
<ul>
<li>[952, 933, 963, 287]</li>
<li>[951, 948, 956, 280] </li>
<li>[945, 945, 963, 282]</li>
<li>[949, 951, 933, 302]</li>
<li>[943, 948, 969, 275]</li>
<li>[951, 937, 950, 297]</li>
</ul>
<p><strong>Data/Features</strong></p>
<p>I then collected daily, weekly, and monthly features from <a href="https://fred.stlouisfed.org/" target="_blank">Fred</a>, and used data up until the 14th of each month (the day the competition would end). Some of these features came from the <a href="https://fred.stlouisfed.org/release?rid=10" target="_blank">Consumer Price Index Data</a> and <a href="https://fred.stlouisfed.org/release?rid=454" target="_blank">Average Price Data</a> which were released on the morning of the competition deadline.</p>
<p><strong>Thoughts</strong></p>
<p>My biggest concern here is data leakage. I tried to make sure that each feature was “known at the time of prediction”, and I hope I caught all data leaks when calculating my CV. (2nd biggest concern is overfitting economic indicators)</p>
<p><strong>CV Score</strong></p>
<p>The average SMAPE scores I calculated on the last 5 months of 2022 for each cluster are as follows. The ENS score takes an average of the 6 model predictions. </p>
<table>
<thead>
<tr>
<th></th>
<th>Last</th>
<th>Ens</th>
<th>_008E</th>
<th>_007E</th>
<th>_049N</th>
<th>dp_pc</th>
<th>9_pct</th>
<th>c_max</th>
</tr>
</thead>
<tbody>
<tr>
<td>0-step</td>
<td>2.8514</td>
<td><strong>2.5820</strong></td>
<td>2.6108</td>
<td>2.6638</td>
<td>2.6660</td>
<td>2.6590</td>
<td>2.6506</td>
<td>2.6436</td>
</tr>
<tr>
<td>1-step</td>
<td>3.4091</td>
<td><strong>2.6355</strong></td>
<td>2.7057</td>
<td>2.6922</td>
<td>2.7026</td>
<td>2.7047</td>
<td>2.7245</td>
<td>2.7082</td>
</tr>
<tr>
<td>2-step</td>
<td>4.1169</td>
<td><strong>2.8772</strong></td>
<td>2.9679</td>
<td>2.9728</td>
<td>2.9056</td>
<td>2.9673</td>
<td>2.9920</td>
<td>2.9623</td>
</tr>
<tr>
<td>Total</td>
<td>3.4592</td>
<td><strong>2.6982</strong></td>
<td>2.7615</td>
<td>2.7762</td>
<td>2.7580</td>
<td>2.7770</td>
<td>2.7890</td>
<td>2.7714</td>
</tr>
</tbody>
</table> |
GoDaddy - Microbusiness Density Forecasting | ETS, Linear Models, and MARS | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Below is a brief description + thoughts on my forecasting solution.<br>
<strong>Private LB Place</strong>: 122/3,546<br>
<strong>Private LB Score</strong>: 3.9884<br>
<strong>Code</strong>: <a href="https://www.kaggle.com/code/abandura/mbd-forecasting-w-mars-lms-r" target="_blank">https://www.kaggle.com/code/abandura/mbd-forecasting-w-mars-lms-r</a></p>
<p>Thanks to everyone who shared their insights and code!</p>
<h2>Pre-Processing</h2>
<p>Many counties exhibit level shifts in their historical microbusiness density, which reduces overall accuracy if simply included in the modeling process. I separated these from the rest of the counties by identifying any counties with a month-to-month change greater than 25%, and simply used last value predictions for them. Many other contestants took a similar approach. Looking at the size distribution of these counties (visualized in the histogram below) we can see that it excludes most of the smallest counties as well as a group of larger volume counties.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F13474157%2F12985b7771d35940abaa8a6db8e72484%2Fexcl_cfips.png?generation=1687123492757230&alt=media" alt=""></p>
<p>Small counties are unpredictable, as a single domain registration can dramatically change the density. However, looking at the larger counties with high variance it's clear that there is still a strong signal in many of them that could be leveraged for better predictions than a simple last value. For example, county ID 24013 has only one level shift up early on in the data set, and data before that shift could be removed and then interpolated so that it could be included in the forecast model training/prediction process. County IDs 10003 and 32510 have two level shifts that creates a "hump", which could be corrected in a similar manner using interpolation. I had planned to implement an algorithm to correct shifts for these larger counties, but unfortunately ran out of time. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F13474157%2F6b3c0541a03e4f405b1aa745b943d5b6%2Flarge_excl_cfips.png?generation=1687123510916081&alt=media" alt=""></p>
<p>Like many others, I also made the "percent change" adjustment to microbusiness density before training so that loss metrics like RMSE would weight small counties higher in the same way that SMAPE does. I used that adjusted target for all training other than the linear models, because they can be flexibly trained to directly minimize SMAPE (as described below).</p>
<h2>Traditional Time-Series Forecasting, and other features</h2>
<p>Of the traditional autoregressive time-series forecasting methods (ARIMA, Holt-Winters, Exponential Smoothing, etc.) that I tried, Exponential Smoothing (ETS) was the best. I ended up using ETS forecasts as features for the linear modeling by rolling through the data and generating ets forecasts for 1-6 month time horizons.</p>
<p>Other features I toyed with included moving-average terms, difference terms, month and year, and the average of all previous MB density values. </p>
<h2>CV Strategy</h2>
<p>For CV I used the last 6 months of data, as shown below, and trained separate models for each forecast horizon. I wanted to use as much data as possible for training, since we only had a few years of historical data spanning the pandemic.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F13474157%2F6ae7279f1d78b31a125355f0c2d34cd8%2Fcv_strategy.png?generation=1687123527511586&alt=media" alt=""></p>
<h2>Linear Modeling via Optimization</h2>
<p>I tried other ML approaches like XGBoost, but found the most success with the simpler linear models.</p>
<p>Another nice feature of linear models is you can directly fit them to minimize SMAPE by solving the optimization problem with the following objective:</p>
<pre><code>
fn par df r_cols y norm_col l2 l1
preds par df.N
l2p
l1p
ind par
i_col r_colsind
preds preds parinddf geti_colmeangeti_colsdgeti_col
l2p l2p l2parind
l1p l1p l1parind
err smapeadfgety fcpreds l1p l2p
err
</code></pre>
<p>I tested L1 and L2 regularization, but found the lowest CV accuracy with no regularization. Looking at the fitted weight magnitudes, it seems that MA terms are most important in the forecasts. This was my best-scoring final submission.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F13474157%2F8b4a56ee77fff6fe87562ab6916726f5%2Flm_weights.png?generation=1687130521279924&alt=media" alt=""></p>
<h2>Multivariate adaptive regression spline (MARS)</h2>
<p><a href="https://en.wikipedia.org/wiki/Multivariate_adaptive_regression_spline" target="_blank">https://en.wikipedia.org/wiki/Multivariate_adaptive_regression_spline</a></p>
<p>Because I had success with the LMs, I though that MARS would be a natural improvement since it is an algorithm for fitting piecewise linear models to automatically deal with non-linearities and incorporate variable interactions.</p>
<p>I did some hyperparameter tuning, but had the most success with the default parameters, and based on the CV accuracy I hoped it would outperform the LMs. However that wasn't the case with the private LB (I'm still not sure why, perhaps MARS was more sensitive to erroneous Dec data…)</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F13474157%2Fb41c10f7948ea74940de90bd4e8f357a%2Fsmape_comp.png?generation=1687127830752749&alt=media" alt=""></p> |
GoDaddy - Microbusiness Density Forecasting | Giba RAPIDS SVR Solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>For my first solution I used a global linear multiplier were I pick the coefficient optimizing SMAPE for each split month and forecast span separately.</p>
<p>The second solution is based in SVR. You can check my notebook here: <a href="https://www.kaggle.com/code/titericz/super-fast-rapids-svr/notebook" target="_blank">Super Fast RAPIDS SVR</a></p>
<p>Once <code>microbusiness_density</code> can be calculated using <code>active</code> and <code>county population</code>, I used <code>active</code> as the target labels in my models.<br>
For validation I used last 12 months to calculate the SMAPE for each forecast range. To ease development I tracked only the gain each algorithm gives compared with last value benchmark. For example, predicting 3 months ahead with last value gives SMAPE 2.717, if my algorithm scores 2.617, then the gain will be 0.10 over the baseline.</p>
<p>The SVR gain for each forecast period is:</p>
<table>
<thead>
<tr>
<th>Forecast</th>
<th>SMAPE Gain(12 months avg)</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0.0171</td>
</tr>
<tr>
<td>2</td>
<td>0.0611</td>
</tr>
<tr>
<td>3</td>
<td>0.1555</td>
</tr>
<tr>
<td>4</td>
<td>0.2621</td>
</tr>
<tr>
<td>5</td>
<td>0.3524</td>
</tr>
<tr>
<td>6</td>
<td>0.4750</td>
</tr>
</tbody>
</table>
<p>As you can see the gain is not much. But all other algorithms I tried (including GBDTs) scored worse than SVR in my approach.</p>
<h1>Other than that I wish good luck to everyone that dedicated time to this competition! 😉</h1>
<p>obs. </p>
<ul>
<li>notebook V1 using sklearn SVR in 4607s.</li>
<li>notebook V2 using RAPIDS SVR 136s. (34x faster 💪)</li>
</ul>
<p>SVR around ~20-30% better than XGB/LGB. </p> |
GoDaddy - Microbusiness Density Forecasting | Godday's Solution that didn't Appear in Public Notebooks. | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you that you like it. If my solution works well in Private LB, I will share my code.</p>
<p>Yes, it is quite strange. However, my CV result on 5th month is 3.15, which is more reasonable and reliable.</p>
<p>Thank you. I think your work gets a much better CV score than mine, congrats. <a href="https://www.kaggle.com/tarique7" target="_blank">@tarique7</a> </p>
<p>This competition is full of positions, and I don't know if I can get a good result in the end. But I figured I'd forget about the game if I waited another 3 months, so I decided to share my solution anyway.</p>
<h2>0. Preface:</h2>
<p>Hi all people diving in this competition,</p>
<p>We had a very memorable racing experience together (at least for me). I learned a lot from this competition, and to be honest, I'm just a newbie in machine learning and time series research. I met a lot of talent here <a href="https://www.kaggle.com/cdeotte" target="_blank">@cdeotte</a> <a href="https://www.kaggle.com/kaggleqrdl" target="_blank">@kaggleqrdl</a> <a href="https://www.kaggle.com/joshuascj" target="_blank">@joshuascj</a> <a href="https://www.kaggle.com/titericz" target="_blank">@titericz</a> <a href="https://www.kaggle.com/batprem" target="_blank">@batprem</a> <a href="https://www.kaggle.com/vitalykudelya" target="_blank">@vitalykudelya</a> . Too many friends for me to put them all here.<br>
They kindly shared good baselines, ideas and data, which taught me a lot. I must say that we have reached such score by standing on the shoulders of giants.</p>
<h2>1. solution:</h2>
<h3>1.1. ideas</h3>
<p>Our team used GRU blending with XGBoost as a solution.<br>
The composition of time series data is probably: (this is my understanding, I hope there is no error in expression)</p>
<p>$$timeseries=trend+otherinformantion+noise$$</p>
<p>The general idea is to use GRU to capture the "trend" information of the data, and XGBoost to capture "other information".</p>
<p>Expressed in pseudocode:</p>
<p><strong>Fit stage</strong></p>
<p><code>GRU. fit(trend_data)</code><br>
<code>XGB.train(X_XGB[other_information_features], residual_data)</code></p>
<p><strong>Inference stage</strong><br>
<code>residual_data_pred=XGB.predict(X_XGB[other_information_features])</code><br>
<code>trend_data_pred = GRU. predict(X_GRU)</code><br>
<code>sub_data_pred=trend_data_pred +residual_data_pred</code></p>
<h3>1.2. Cross-validation</h3>
<ol>
<li>When we train GRU, I predict 5 months totally. I use rolling-window CV method for 5 times.</li>
</ol>
<p><strong>Results:</strong> 1st month: 1.333; 3rd month: 2.47; 4th month: 2.95; 5th month: 3.39</p>
<ol>
<li>When we train XGB, we use Group CV results for 3 times.<br>
<strong>Results:</strong> 1st month: Nan; 3rd month: 2.34; 4th month: 2.74; 5th month: 3.12</li>
<li>Improve:</li>
<li><strong>Results:</strong> 1st month: Nan; 3rd month: 0.13; 4th month: 0.20; 5th month: 0.26</li>
</ol>
<h3>1.3. LB tests:</h3>
<p>Also, I use LB to determine my CV’s performance.<br>
I treat January (LB) as "March", "April" and "May" respectively to output the results. (Just slide the GRU forecast starting point backwards from 2022-12-01.)</p>
<p><strong>Only GRU results:</strong> 3rd month: 2.82, 4th month: 3.15, 5th month: 3.4</p>
<p><strong>GRU blending XGB</strong>: 3rd month: 2.66, 4th month:2.8, 5th month: 2.5</p>
<p><strong>Improve</strong>: 3rd month: 0.16, 4th month:0.35, 5th month: 0.9 (Maybe this is somehow the luck)</p>
<h3>1.4. Conclusion</h3>
<p>Both CV score and LB score all get improvement. XGB can help GRU. Thank you. <br>
Good luck to us.</p>
<p>Trends do not exist in every county, but most counties with high active/popularity have trends, (up or down). But there are a small number of (very few) towns with very low activity that also have a relatively stable upward trend. </p>
<p>My model tells me that the overall/global trend is all up, but slightly. Somehow it is similar to the Linear Model results, that's why linear model works well in this competition I guess.</p>
<p>As analyzed by many Kagglers, last value is a good choice for small counties, because small county didn't have a stable trend. Instead of guessing whether they will rise or fall in the future, it is better to keep the current value unchanged and you may get more Good SMAPE.</p>
<p>Thank you for your comment! <a href="https://www.kaggle.com/cpmpml" target="_blank">@cpmpml</a> Yes, my solution is quite similar to yours, because I did browse your code before I implement my solution. It did work to improve GRU.</p>
<p>thank you for your good wishes! <a href="https://www.kaggle.com/siddharthkumarsah" target="_blank">@siddharthkumarsah</a> . I hope my solution can get a satisfied result, but there are so many talents in this competition. Anyway, wish us good luck.</p> |
GoDaddy - Microbusiness Density Forecasting | My Forecasting Strategy | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Trend</h1>
<p>My cross-validation didn't show that complicated gradient boostings showed significantly better results than simple approaches. Also for some months gradient boostings performed worse than the Last Value baseline and simple approaches showed more stable performance. </p>
<p>The following formula shows how I estimated trend for cfips.<br>
<code>active_quantile_group_21_last_6m_trend</code> means the best multiplication constant (clipped from 1 to 1.006) for the last value of <code>microbusiness_density</code> for the next month on a previous 6 month for a group of cfips (total 21 groups by quantile of active). The same logic for <code>state</code> and concrete <code>cfips</code> group.<br>
<code>forward_2</code> means the best multiplication constant for the next 2 month (clipped from 1 to 1.012).</p>
<pre><code>df_features_data[] = (
df_features_data[] *
+ df_features_data[] *
+ df_features_data[] * + df_features_data[] *
+ df_features_data[] * + df_features_data[] *
) * + ((
df_features_data[] *
+ df_features_data[] *
+ df_features_data[] *
)**) *
</code></pre>
<h1>Using the best public submission as a starting point for predictions</h1>
<p>Public Leaderboard data wasn't published and for time-series data it should be beneficial to use the best public submission.</p>
<h1>Select 2 Submissions. Positive and Negative</h1>
<p>It's a good idea to cover different scenarios selecting 2 submissions. I call it Positive submission (we under-forecasting trend) and negative (we over-forecasting trend). <br>
For example for Positive submission <code>* (trend + 0.0005)**(month_number)</code></p>
<h1>May Seasonality</h1>
<p>I just used forecast for April <code>* (1 - 0.0025)</code> for Positive submission, because May showed a dropdown of values the last two years.</p>
<h1>Cfips with active < 150</h1>
<p>My cross-validation showed that using the last value baseline for such cfips (as many public baselines do) is good only for one month forward forecast, for March, April, May i used some multiplication constants.<br>
The following plot shows that for active < 75 using the last value baseline for 3 month forecast is the best, for 75-150 it's better to use trend.
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F297456%2F7059d3c2b37887d58d0ae4b88dd4cb4d%2Fnewplot%20(98).png?generation=1678841088819412&alt=media" alt=""></p>
<h1>Hope that random helps 🤞</h1> |
GoDaddy - Microbusiness Density Forecasting | My Strategy & The Dangers of Public Notebooks | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Yes, this is a really good point I didn't bring up in my original post and something that I was careful to do. Once I predicted a new value, the main features I had to update for my notebook were the lag features. Since I used lagged active features too, this also required me to compute the active feature for each predicted time step from the predicted value and the 2020 population (later adjusted with the 2021 population) via the following code:</p>
<pre><code>active_mask = (raw["dcount"] == (TS + 1))
raw.loc[active_mask, "active"] = ((raw.loc[active_mask, "pop2020"] * raw.loc[active_mask, "ypred"]) / 100).astype(int)
</code></pre>
<p>Then updating the lag features with a function I made: <code>raw = update_lags(raw)</code></p>
<p>Thanks for your comment! </p>
<p>I'm not 100% sure what you mean by reusing the model many times. If I understand correctly, "reusing the last value model many times, and generating several predictions" is indeed what I did and what I meant when I said "autoregressively" generate predictions. Like most models, this likely has it's upsides and downsides. From my analysis, there seems to be a left-skew in the distribution of my predicted values (thus my predictions will tend to be more positive than negative). As an alternative method, it seems other people like <a href="https://www.kaggle.com/joshuascj" target="_blank">@joshuascj</a> used models trained with "gaps" to predict the following months, find his explanation <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/394822" target="_blank">here</a>. </p>
<p>Hello everyone,</p>
<p>I may not have the best performing model or the most clever, but I thought I would share my strategy for people interested. Prior to this competition I had no time series experience and learned a ton during this competition, so thanks to everyone who made their notebooks public and shared their ideas. My strategy consists of two different strategies/models. </p>
<p>Things I tried that did not work: GRU's, linear regression models (I had to be too selective with counties to get good performance), and traditional autoregressive models like ARMA didn't work for me. If anyone got these to work well, I'de love to hear how you did it. </p>
<p><strong>First model:</strong> My first model is just a “last value” model and is meant to be a hedge against my main model. The strategy was this: Overfit the leaderboard to leak back the best values to use for a “last value” model. I figure since most public notebooks work via predicting the first value of the public lb and just repeating that value, then I should be in a pretty decent place if I can outperform the top public notebooks in the public LB (although there are no guarantees this will outperform in private LB).</p>
<p><strong>Second model:</strong> My second model was a modified version of this notebook:</p>
<ul>
<li><a href="https://www.kaggle.com/code/vadimkamaev/micro-business-catboost" target="_blank">Micro-Business. Catboost</a>. </li>
</ul>
<p>For my modifications I did the following:</p>
<ol>
<li><p>First I performed a custom preprocessing scheme that I built, followed by another preprocessing scheme from the popular <a href="https://www.kaggle.com/code/titericz/better-xgb-baseline" target="_blank">Better XGB Baseline</a> notebook. More information on my preprocessing scheme can be found in my notebook explaining it here: <a href="https://www.kaggle.com/competitions/godaddy-microbusiness-density-forecasting/discussion/393364" target="_blank">Outliers, Changepoints, and Smoothing</a></p></li>
<li><p>Next, rather than only predicting the first value, I modified the code to autoregressively predict each value in the testing set. </p></li>
<li><p>I incorporating the ideas in the following notebook: <a href="https://www.kaggle.com/code/vitalykudelya/use-discrete-nature-of-microbusiness-density" target="_blank">Use Discrete Nature of microbusiness_density</a></p></li>
<li><p>I removed the meta model and just did a threefold ensemble of an XGBoost, CatBoost, and LGBM model. </p></li>
<li><p>Tons of other "micro-adjustments" to preprocessing, feature engineering, training, and postprocessing.</p></li>
<li><p>Removed "suspicious" looking code. See the topic below.</p></li>
</ol>
<p><strong>On the Dangers of Public Notebooks:</strong></p>
<p>It seems that the five best scoring public notebooks (maybe more, I stopped looking after five) have a fatal flaw in their submissions resulting from the following code at the bottom of each notebook:</p>
<pre><code>for i, row in sub.iterrows():
test.iat[i,1] = (
0.65*test.iat[i,1] +
0.35*row["microbusiness_density"]
)
test.to_csv('submission.csv', index=False)
test.head()
</code></pre>
<p>This block of code will essentially cause all the “private LB” values to be 0.35 times the last predicted public LB value. Therefore, if users who blindly copied the top public notebooks didn’t check for this, their models will likely not generalize to the private LB data. Whether this was done intentionally or not, I do not know. In total, these notebooks had 2545 copies and edits (likely from a lot of the same people copying). Below is a sample from these submissions.</p>
<table>
<thead>
<tr>
<th>row_id</th>
<th>microbusiness_density</th>
</tr>
</thead>
<tbody>
<tr>
<td>1001_2022-11-01</td>
<td>3.404743687834736</td>
</tr>
<tr>
<td>1001_2022-12-01</td>
<td>3.422746298213241</td>
</tr>
<tr>
<td>1001_2023-01-01</td>
<td>3.3372338989153425</td>
</tr>
<tr>
<td>1001_2023-02-01</td>
<td>1.1679193483055044</td>
</tr>
<tr>
<td>1001_2023-03-01</td>
<td>1.1679193483055044</td>
</tr>
<tr>
<td>1001_2023-04-01</td>
<td>1.1679193483055044</td>
</tr>
<tr>
<td>1001_2023-05-01</td>
<td>1.1679193483055044</td>
</tr>
<tr>
<td>1001_2023-06-01</td>
<td>1.1679193483055044</td>
</tr>
</tbody>
</table>
<p>Best of luck in the coming months!</p>
<p>Ryan P.</p> |
GoDaddy - Microbusiness Density Forecasting | Public 1125 - > Private 48 solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Methods that are beneficial for prediction:</p>
<p>Outlier smoothing<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5998972%2Fbc31d3c4fcf04c23e7afb091f931984b%2F1.png?generation=1687061025743863&alt=media" alt=""><br>
Coefficient adjustment + approximation<br>
active: The raw count of microbusinesses in the county The target to be predicted is population density = active / population. The population statistics change every January. The competition requires predicting the population density in 2023, which has changed in the denominator of population density. Based on the existing data, use (2023 predicted value * 2020 population) / 2021 population to estimate the coefficient of population trend change, and then correct the predicted value with this coefficient. Because the numerator part active is originally an integer, the predicted value multiplied by the population is usually a continuous value, such as 1.3, while the actual value may be 1, and rounding can help increase accuracy. The predicted value after coefficient correction should be multiplied by the 2021 population, then rounded, and then divided by the 2021 population for further correction.</p>
<p>Optimal shift time = 12<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5998972%2Fc78306ebaa11dbf3adbc2c6a1d6a1b62%2F2.png?generation=1687061119239898&alt=media" alt=""><br>
Create lagged features for the past 12 months, if it is 24 or 6, it will make the effect worse, especially 24.</p>
<p>The state and county fields are label encoded, plus the cfips field (equivalent to state + county), which are beneficial for the prediction results. <br>
Rate of change effect is better<br>
For predicting n + gap tasks, change the original density continuous value to be predicted to the growth value between the current value and the previous gap months.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5998972%2F9c4f2fa8203de8a5e29cc538e1dfccb8%2F3.png?generation=1687061133256397&alt=media" alt=""><br>
Make some lagged features for the original density continuous value, and then add some lagged features for this growth value, which improves the prediction accuracy</p>
<p>After converting the density target value into a growth value, LightGbm and Xgboost models need to change the default objective parameter and use pseudo huber loss as the optimization indicator.</p>
<p>========</p>
<p>对预测有增益的方法:</p>
<h1>异常值平滑</h1>
<h1>系数调整 + 求近似值</h1>
<p>active:The raw count of microbusinesses in the county<br>
要预测的目标为人口密度 = active / 人口。 人口统计值每年一月会发生变化。竞赛要预测2023年的人口密度,在人口密度分母上已经发生了变化。基于已有的数据,使用(2023年预测值 * 2020年人口)/ 2021年人口 估算出人口趋势变化的系数,再将该系数修正预测值。<br>
因为分子部分active本来是整数,预测值乘以人口通常是连续值,譬如1.3,而实际值可能是1,取整后可以帮助精度增加。系数修正后的预测值要乘以2021年人口,然后取整,再除以2021年人口,做进一步修正。</p>
<h1>最优shift time = 12</h1>
<p>创建过去12个月的滞后特征,如果是24或者6,都会让效果变差,尤其是24.</p>
<h1>state和county两个字段做label encoding,加上cfips(等同于state + county)字段,都对预测结果有增益。</h1>
<h1>rate of change 效果变好</h1>
<p>1.预测n + gap的任务,将原本要预测的密度连续值, 改成当前值与上gap个月的增长值。</p>
<p>2.对原本对密度连续值做一些滞后特征,再加上对该增长值做滞后特征,对预测准度有提升<br>
3.将密度目标值转换成增长值后,LightGbm和Xgboost模型需要更改默认的objective参数,使用pseudo huber loss作为优化指标.</p> |
GoDaddy - Microbusiness Density Forecasting | Public 531st -> Private 10th: The Complete Solution Code | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: GoDaddy - Microbusiness Density Forecasting
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1><strong>GoDaddy - Microbusiness Density Forecasting</strong></h1>
<p>The solution is 3 months ago, so if there is anything missing, please let me know.</p>
<p>The objective of the competition is to predict monthly <strong>microbusiness density</strong> in <strong>3315 cfips</strong> (County FIPS) in the United States. The code implementation incorporates several special features and techniques to improve the accuracy of the predictions.</p>
<h2><strong>Approach</strong></h2>
<h3><strong>1. Predicting 3315 Time Series</strong></h3>
<p>This approach predicts the microbusiness density for each of the <strong>3315 cfips</strong> individually. This allows for more granular and accurate predictions tailored to specific regions.</p>
<h3><strong>2. Technical Indicators</strong></h3>
<p>The code utilizes popular technical indicators such as <strong>Exponential Moving Average (EMA)</strong>, <strong>Momentum (MOM)</strong>, and <strong>Relative Strength Index (RSI)</strong>. These indicators capture underlying trends, momentum, and market conditions, enhancing the predictive power of the model.</p>
<h3><strong>3. External Datasets</strong></h3>
<p>In addition to the microbusiness density data, the model incorporates several external datasets. These datasets include information such as <strong>unemployment data</strong>, <strong>earnings</strong>, <strong>rent</strong>, <strong>DSG10</strong>, <strong>tax rate</strong>, <strong>housing price</strong>, and <strong>population estimates</strong>. By incorporating these relevant external factors, the model can capture the influence of broader economic and demographic factors on microbusiness density.</p>
<h3><strong>4. Optuna for Hyperparameter Optimization</strong></h3>
<p><strong>Optuna</strong> is used to minimize the <strong>SMAPE</strong> in the <strong>Catboost</strong> model.</p>
<h3><strong>5. Catboost Model with Cross Validation</strong></h3>
<p>The code employs the <strong>Catboost model</strong>. Also used <strong>Cross Validation (CV)</strong> to generalize well to unseen data.</p>
<h3><strong>6. Multiple Model Training</strong></h3>
<p>To predict multiple future time periods, five separate models are trained. Each model is designed to predict a specific time horizon, such as <strong>t+1 month</strong>, <strong>t+2 months</strong>, and so on.</p>
<h3><strong>7. External Dataset Addition</strong></h3>
<p>The code "<strong>6-external-datasets.ipynb</strong>" is found on Kaggle and is provided to incorporate additional external datasets into the prediction model.</p>
<h2><strong>Limitations</strong></h2>
<ul>
<li><strong>Limited Historical Data</strong>: The current approach utilizes only the past three months of data to predict future microbusiness density. Exploring longer intervals of historical data could provide additional context and potentially improve the forecasting accuracy.</li>
</ul>
<h2><strong>Code Files</strong></h2>
<ul>
<li><p><strong>6-external-datasets.ipynb</strong>: add additional external datasets to the prediction model. It can be found on Kaggle and is intended to enhance the feature set.</p></li>
<li><p><strong>kaggle_competition_microbusiness.ipynb</strong>: contains the full model training code for microbusiness density prediction. It encompasses data preprocessing, model training using <strong>Catboost</strong> and <strong>Optuna</strong>, and evaluation using <strong>SMAPE</strong>.</p></li>
</ul>
<p><strong>Github link</strong>: <a href="https://github.com/ttterence927/kaggle_competition_microbusiness/" target="_blank">https://github.com/ttterence927/kaggle_competition_microbusiness/</a></p>
<h2><strong>Show Your Support</strong></h2>
<p>If you find this code implementation valuable or interesting, please consider giving it a star on <strong>GitHub</strong>.</p>
<p>Thank you :)) Learned a lot from you and all the people here. And congrats on winning 1st place!!</p> |
Google - American Sign Language Fingerspelling Recognition | 122nd Solution for Google - American Sign Language Fingerspelling Recognition Competition | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>We did this in our freshman summer, defintely learnt a lot.</p>
<p><strong>Context</strong></p>
<ul>
<li>Business context:<a href="https://www.kaggle.com/competitions/asl-fingerspelling/overview" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/overview</a></li>
<li>Data context:<a href="https://www.kaggle.com/competitions/asl-fingerspelling/data" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/data</a></li>
</ul>
<p><strong>Overview of the Approach</strong><br>
Our work is basically some improvements based on the <a href="https://www.kaggle.com/code/royalacecat/the-deeper-the-better" target="_blank">public notebook baseline</a> w/ LB score 0.699, and we improved it w/ +0.007.<br>
It conbines Transformer and 1D-CNN.<br>
We basically improved it by doing some feature engineering to the frames.</p>
<p><strong>Details on the Submission</strong><br>
Originally our work was based on another public notebook baseline which only uses the Transformer, and we did some improvement on that by rescheduling the learning rate, specifically, to increase the learning rate at the end, but it didn't work for our final notebook.<br>
We also processed the supplemental data, but it didn't have some improvements(maybe we did it the wrong way).<br>
Our data augmentation includes some techniques like random cropping, rotation, affine transformations, etc.</p>
<p><strong>Code Samples for Data Augmentation</strong></p>
<pre><code>@tf.function()
def :
tf.[0] < FRAME_LEN:
x = tf.pad(x, ([[, FRAME_LEN-tf.shape(x)[]], [, ], [, ]]), constant_values=())
:
x = tf.image.resize(x, (FRAME_LEN, tf.shape(x)[]))
x
@tf.function()
def resize_pad_channel(x):
tf.shape(x)[] < FRAME_LEN:
x = tf.pad(x, ([[, FRAME_LEN-tf.shape(x)[]], [, ], [, ]]), constant_values=())
:
x = tf.image.resize(x, (FRAME_LEN, tf.shape(x)[]))
x
def interp1d_(x, target_len, method=):
target_len = tf.maximum(,target_len)
method == :
tf.random.uniform(()) < :
x = tf.image.resize(x, (target_len,),)
:
tf.random.uniform(()) < :
x = tf.image.resize(x, (target_len,),)
:
x = tf.image.resize(x, (target_len,),)
:
x = tf.image.resize(x, (target_len,),method)
resize_pad(x)
def flip_lr(x):
dx, dy, dz = tf.unstack(x, axis=)
dx = -dx
new_x = tf.([dx,dy,dz], )
new_x
def resample(x, rate=(,)):
rate = tf.random.uniform((), rate[], rate[])
length = tf.shape(x)[]
new_size = tf.cast(rate*tf.cast(length,tf.float32), tf.int32)
new_x = tf.image.resize(x, (new_size, ))
resize_pad_channel(new_x)
def spatial_random_affine(xyz,
scale = (,),
shear = (,),
shift = (,),
degree = (,),
):
center = tf.constant([,])
scale is not None:
scale = tf.random.uniform((),*scale)
xyz = scale*xyz
shear is not None:
xy = xyz[...,:]
z = xyz[...,:]
shear_x = shear_y = tf.random.uniform((),*shear)
tf.random.uniform(()) < :
shear_x =
:
shear_y =
shear_mat = tf.identity([
[,shear_x],
[shear_y,]
])
xy = xy @ shear_mat
center = center + [shear_y, shear_x]
xyz = tf.concat([xy,z], axis=)
degree is not None:
xy = xyz[...,:]
z = xyz[...,:]
xy -= center
degree = tf.random.uniform((),*degree)
radian = degree/*np.pi
c = tf.math.(radian)
s = tf.math.(radian)
rotate_mat = tf.identity([
[c,s],
[-s, c],
])
xy = xy @ rotate_mat
xy = xy + center
xyz = tf.concat([xy,z], axis=)
shift is not None:
shift = tf.random.uniform((),*shift)
xyz = xyz + shift
xyz
def temporal_crop(x, length=FRAME_LEN):
l = tf.shape(x)[]
offset = tf.random.uniform((), , tf.clip_by_value(l-length,,length), dtype=tf.int32)
x = x[offset:offset+length]
x
def temporal_mask0(x, size=(,), mask_value=()):
l = tf.shape(x)[]
mask_size = tf.random.uniform((), *size)
mask_size = tf.cast(tf.cast(l, tf.float32) * mask_size, tf.int32)
mask_offset = tf.random.uniform((), , tf.clip_by_value(l-mask_size,,l), dtype=tf.int32)
x = tf.tensor_scatter_nd_update(x,tf.range(mask_offset, mask_offset+mask_size)[...,None],tf.fill([mask_size,,],mask_value))
x
def temporal_mask(x, rate=, mask_value=()):
mask_size=(FRAME_LEN*rate)
mask = tf.squeeze(tf.random.categorical(np.mat([/FRAME_LEN i in range(FRAME_LEN)]),mask_size))
x = tf.tensor_scatter_nd_update(x,mask[...,None],tf.fill([mask_size,,],mask_value))
x
def spatial_mask(x, size=(,), mask_value=()):
mask_offset_y = tf.random.uniform(())
mask_offset_x = tf.random.uniform(())
mask_size = tf.random.uniform((), *size)
mask_x = (mask_offset_x<x[...,]) & (x[...,] < mask_offset_x + mask_size)
mask_y = (mask_offset_y<x[...,]) & (x[...,] < mask_offset_y + mask_size)
mask = mask_x & mask_y
x = tf.where(mask[...,None], mask_value, x)
x
def augment_fn(x, always=False):
tf.random.uniform(())< or always:
x = resample(x, (,))
tf.random.uniform(())< or always:
x = flip_lr(x)
tf.random.uniform(())< or always:
x = spatial_random_affine(x)
tf.random.uniform(())< or always:
x = temporal_mask(x)
tf.random.uniform(())< or always:
x = spatial_mask(x)
x
@tf.function(jit_compile=True)
def pre_process0(x):
lip_x = tf.gather(x, LIP_IDX_X, axis=)
lip_y = tf.gather(x, LIP_IDX_Y, axis=)
lip_z = tf.gather(x, LIP_IDX_Z, axis=)
rhand_x = tf.gather(x, RHAND_IDX_X, axis=)
rhand_y = tf.gather(x, RHAND_IDX_Y, axis=)
rhand_z = tf.gather(x, RHAND_IDX_Z, axis=)
lhand_x = tf.gather(x, LHAND_IDX_X, axis=)
lhand_y = tf.gather(x, LHAND_IDX_Y, axis=)
lhand_z = tf.gather(x, LHAND_IDX_Z, axis=)
rpose_x = tf.gather(x, RPOSE_IDX_X, axis=)
rpose_y = tf.gather(x, RPOSE_IDX_Y, axis=)
rpose_z = tf.gather(x, RPOSE_IDX_Z, axis=)
lpose_x = tf.gather(x, LPOSE_IDX_X, axis=)
lpose_y = tf.gather(x, LPOSE_IDX_Y, axis=)
lpose_z = tf.gather(x, LPOSE_IDX_Z, axis=)
lip = tf.concat([lip_x[..., tf.newaxis], lip_y[..., tf.newaxis], lip_z[..., tf.newaxis]], axis=)
rhand = tf.concat([rhand_x[..., tf.newaxis], rhand_y[..., tf.newaxis], rhand_z[..., tf.newaxis]], axis=)
lhand = tf.concat([lhand_x[..., tf.newaxis], lhand_y[..., tf.newaxis], lhand_z[..., tf.newaxis]], axis=)
rpose = tf.concat([rpose_x[..., tf.newaxis], rpose_y[..., tf.newaxis], rpose_z[..., tf.newaxis]], axis=)
lpose = tf.concat([lpose_x[..., tf.newaxis], lpose_y[..., tf.newaxis], lpose_z[..., tf.newaxis]], axis=)
hand = tf.concat([rhand, lhand], axis=)
hand = tf.where(tf.math.is_nan(hand), , hand)
mask = tf.math.not_equal(tf.reduce_sum(hand, axis=[, ]), )
lip = lip[mask]
rhand = rhand[mask]
lhand = lhand[mask]
rpose = rpose[mask]
lpose = lpose[mask]
lip, rhand,lhand, rpose, lpose
@tf.function()
def pre_process1(lip, rhand,lhand, rpose, lpose, augment = False):
lip = (resize_pad(lip) - LIPM) / LIPS
rhand = (resize_pad(rhand) - RHM) / RHS
lhand = (resize_pad(lhand) - LHM) / LHS
rpose = (resize_pad(rpose) - RPM) / RPS
lpose = (resize_pad(lpose) - LPM) / LPS
x = tf.concat([lip, rhand, lhand, rpose, lpose], axis=)
x = tf.where(tf.math.is_nan(x), , x)
augment:
x = augment_fn(x)
s = tf.shape(x)
x = tf.reshape(x, (s[], s[]*s[]))
x
pre0 = pre_process0(frames)
pre1 = pre_process1(*pre0)
INPUT_SHAPE = (pre1.shape)
print(INPUT_SHAPE)
</code></pre>
<p><strong>Some Useful References</strong><br>
<a href="https://www.kaggle.com/code/royalacecat/the-deeper-the-better" target="_blank">https://www.kaggle.com/code/royalacecat/the-deeper-the-better</a><br>
<a href="https://www.kaggle.com/code/hebasaleh00/aslfr-eda-preprocessing" target="_blank">https://www.kaggle.com/code/hebasaleh00/aslfr-eda-preprocessing</a><br>
<a href="https://www.kaggle.com/competitions/asl-fingerspelling/discussion/409438" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/discussion/409438</a></p> |
Google - American Sign Language Fingerspelling Recognition | 126th Place Solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-inference-python3-7-tpu" target="_blank">This solution</a> is an improved version of <a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference" target="_blank">my public notebook</a> with the following modifications:</p>
<ul>
<li>Running on a TPU to allow for faster training and experimentation</li>
<li>Increased number of input frames 128 → 288</li>
<li>Batch size 64 → 512</li>
<li>Units encoder 384 → 288</li>
<li>Units decoder 256 → 128</li>
</ul>
<p>For an in depth explanation of the approach I refer to the public notebook code and comment section.</p>
<p>The expect the performance boost in my private notebook is mostly due to the decreased model capacity and increased batch size, this should reduce overfitting.</p> |
Google - American Sign Language Fingerspelling Recognition | 17th Solution: Conformer + CTCLoss + 500 epoch training | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>TL; DR</h1>
<p>Fixed-length input (220 frames), padding shorter inputs and resizing longer inputs.<br>
2 layer MLP landmark encoder + 6 layer 384-dim Conformer + 1 layer GRU and 500 epochs training (takes ~8 hours on Kaggle TPUs).<br>
Post-processing (+0.003 in CV and LB) by:</p>
<pre><code> len() <= :
= +
</code></pre>
<p>My notebook is available at <a href="https://www.kaggle.com/code/nightsh4de/ctc-transformer/notebook" target="_blank">https://www.kaggle.com/code/nightsh4de/ctc-transformer/notebook</a><br>
It is primarily based on the previous 1st solution <a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training" target="_blank">https://www.kaggle.com/code/hoyso48/1st-place-solution-training</a> and some public notebooks of this competition:<br>
<a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference#Landmark-Embedding" target="_blank">https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference#Landmark-Embedding</a><br>
<a href="https://www.kaggle.com/code/irohith/aslfr-transformer" target="_blank">https://www.kaggle.com/code/irohith/aslfr-transformer</a> <br>
<a href="https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu" target="_blank">https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu</a>. Many many thanks to them.</p>
<h1>Data Preprocessing and Augmentation</h1>
<p>Basically the same as the previous 1st solution. But I found using 3d positions (means including depth) and pose landmarks gives better CV and LB score.<br>
My input: left-right hand, eye, nose, lips and pose landmarks.</p>
<h1>Model</h1>
<p>I believe this task would be quite similar to Automatic Speech Recognition (ASR), so I used Conformer <a href="https://arxiv.org/abs/2005.08100" target="_blank">https://arxiv.org/abs/2005.08100</a></p>
<h1>Post-preprocessing</h1>
<ol>
<li>I checked my worst predictions in the validation set and found that shorter predictions are worse. And most very short predictions (length less than 5) are basically predicting nothing, e.g. single characters like "a" or space " ".</li>
<li>I found that only few label's length is less or equal to 5. </li>
<li>So adding some make-up phrases to very short predictions might be a good idea.</li>
<li>I picked the most common chars in training set: "a", "e", "r", "o", "-", " ".</li>
<li>I test all the combinations of "a", "e", "r", "o", "-", " " based on validation set and " -aero" is the best.</li>
</ol>
<h1>What not worked</h1>
<ol>
<li>Autoregressive transformer models. <br>
I spent most of my time on transformers. But they strongly overfits the phrase and I couldn't find a way to solve it.<br>
The problem is , for an input X[1…n] and its phrase "123456789". We may expect our model predict "12345" for the first half input X[1…n/2]. <br>
For CTC models, it is true. But my autoregressive model always makes half correct prediction "12345" + half random incorrect prediction e.g. some random 5-digit numbers.</li>
<li>Masking for variable-length input<br>
I tried to use the same masking techniques as the previous 1st solution <a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training" target="_blank">https://www.kaggle.com/code/hoyso48/1st-place-solution-training</a>, to support longer input frames.<br>
However, masking models always produce lower CV and LB scores (-0.02). I believe it is due to the masking limits the output length, but shorter inputs still require a longer output space. Although, unfortunately, I don't have time to verify it, I believe it might enable much better solutions.</li>
<li>Empty embedding for fixed-length input<br>
I tried to use learnable constant weights for padded empty frames and 2-layer MLP for encoding landmarks in original frames. It seems to me makes more sense, but CV score is worse than direct encoding all frames. </li>
</ol>
<p>But masking is faster when processing shorter inputs while being able to take longer inputs without resizing. Am I right?</p> |
Google - American Sign Language Fingerspelling Recognition | 19th Place Solution - Jasper models | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>My solution is quite simple. I wasn't going to write about it, but there are no Jasper-like solutions in discussions yet :)</p>
<h1>Preprocessing</h1>
<p>Preprocessing was almost the same with <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406306" target="_blank">previous competition</a>. But deleted mixup and replace augmentation. And add more complex time augmentations.</p>
<h1>Loss</h1>
<p>I only used CTC loss.</p>
<h1>Data split</h1>
<p>Random split <strong>not</strong> by user for 20 folds grouping by data length.<br>
Deleted obviously bad samples:</p>
<pre><code>supplemental_metadata_df = supplemental_metadata_df[~((supplemental_metadata_df[] < ) &
(supplemental_metadata_df[] > ))]
train_df = train_df[~((train_df[] < ) & (train_df[] > ))]
</code></pre>
<p><br>
Used all supplemental data in train.</p>
<p>Also tried to create second loader with pseudo labels on bad predicted samples. Or delete bad predicted samples. Used both loaders while training:</p>
<pre><code>loader_to_use =
epoch % == :
loader_to_use =
</code></pre>
<p>But it didn't help much.</p>
<h1>Model</h1>
<p>First I tried simple quartznet, but with all strides set to 1.<br>
Then I added some features step by step and trained each experiment from previous best checkpoint.</p>
<h3>Same for all runs:</h3>
<ul>
<li>Optimizer: LookAheadAdamW</li>
<li>Scheduler: Onecycle</li>
<li>Batch size: 80</li>
</ul>
<h3>List of experiments:</h3>
<ul>
<li>Simple 5x5 quartznet with stride = 1. [lr = 8e-3] [epochs=200] CV:0.8035</li>
<li>Simple 5x5 quartznet with stride = 1. [lr = 7e-3] [epochs=150] CV: 0.8106</li>
<li>Previous + SE blocks. [lr = 6e-3] [epochs=171] CV: 0.8160</li>
<li>Previous + Deep supervision (DSV) outputs for train loss. [lr = 5.8e-3] [epochs=175] CV: 0.8211</li>
<li>Previous without DSV + higher aug probabilities. Note: score worse but it needed to train one checkpoint without DSV for better next train results. [lr = 6e-3] [epochs=180] CV: 0.8177</li>
<li>Previous + DSV + increased dropout. [lr = 6.1e-3] [epochs=200] CV: 0.8237</li>
<li>Previous - DSV + lower dropout. [lr = 6e-3] [epochs=173] CV: 0.8188</li>
<li>Previous + Hyper Column (HYP) + 2 more blocks with 5 repeats. [lr=5.8e-3] [epochs=180] CV: 0.8252</li>
<li>Previous + masked 1conv + masked SE + 2D DepthWise CNN layer before classifier + more dropout. [lr=5.8e-3] [epochs=200] CV: 0.8294</li>
<li>Previous + lstm after 2D Conv. [lr=1.75e-3] [epochs=125] CV: 0.8301</li>
</ul>
<h1>What didn't work for me:</h1>
<ul>
<li>Conformer models. I tried it but I guess without enough effort.</li>
<li>Adding attention or conformer blocks to Jasper models.</li>
</ul>
<p>When I used raw conformer and it has very low score. But when I changed input 2D conv to 1D conv or when I just deleted it - it was much better, but still little worse than my Jasper models.</p>
<h1>What I should have done, but didn't:</h1>
<ul>
<li>Train more epochs</li>
<li>Try better with conformer or squeezeformer</li>
<li>Add post processing</li>
<li>Try seq2seq</li>
<li>Fixed length of input</li>
</ul>
<p>Thanks to Kaggle for this great competition. Thanks to all top participants who shared their awesome solutions. <br>
Congratulations to all winners! </p>
<blockquote>
<p>How to enforce fixed length of input?</p>
</blockquote>
<p><a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html" target="_blank">TORCH.NN.FUNCTIONAL.INTERPOLATE</a></p>
<p>Yes, I developed pytorch, and converted it with nobuco. But didn't use Nemo, wrote my own copying some blocks and logic from Nemo.<br>
One of the reasons to write my own - is ability to convert this models with nobuco without a lot of changes</p> |
Google - American Sign Language Fingerspelling Recognition | 20th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to Kaggle, Google and other organizers for hosting this exciting competition. Hope this kinds of competition open in kaggle more often.</p>
<p><strong>TLDR</strong></p>
<p>My solution is a single large model trained with CTC loss with no ensemble(39MB). The output shape of the model is (batch, sentence length, class).</p>
<p><strong>Data Preprocessing and Augmentation</strong></p>
<p>Basically the same as the previous 1st solution. But I found using (x, y, z) and pose landmarks gives better score. I used the following landmarks: left hand, right hand, eye, lips and pose landmarks.</p>
<p><strong>Model</strong></p>
<p>I used previous 1st solution. However, I used the branchformer. Also, I changed the multi head attention to relative multi head attention. My model consists of 1 dense layer - 4 conv1d layer - 6 branchformer layer. In addition, I used stochastic depth.</p>
<p><strong>Training</strong></p>
<p>Epoch = 150<br>
bs = 64<br>
Lr = 8e-4<br>
AWP = Epoch * 0.1<br>
Schedule = CosineDecay with warmup ratio 0.1<br>
Optimizer = Adam with Lookahead<br>
Loss = Inter CTC loss(<a href="https://arxiv.org/abs/2102.03216" target="_blank">https://arxiv.org/abs/2102.03216</a>)</p> |
Google - American Sign Language Fingerspelling Recognition | 22nd place solution: CTC Loss, Strong augmentations, CNN+MHSA | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>The augmentations are applied randomly during training</p>
<p><a href="https://github.com/SamratThapa120/sign-language-finger-spelling/blob/master/signet/models/feature_extractor_downsampled.py" target="_blank">My best-performing model</a> (<a href="https://github.com/SamratThapa120/sign-language-finger-spelling/blob/master/signet/configs/ctc_loss_with_downsampled_deploy_concataug.py" target="_blank">config</a>)is based on the <a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training/notebook" target="_blank">1st place solution of the previous competition</a> by <a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a>. I trained the model using vanilla CTC Loss, and used greedy decoding for inference. </p>
<h3>Things that worked for me:</h3>
<ul>
<li><p><strong>Longer input frames length:</strong> A longer input frame length of 384 performed better than shorter length of 256. </p></li>
<li><p><strong>Deeper/larger model:</strong> My best-performing model has 7 blocks with hidden dimension of 256. It has 9.5M parameters.</p></li>
<li><p><strong>Pose keypoints:</strong> Adding pose information was helpful. Best-performing model uses pose+hands+lips+eyes.</p></li>
<li><p><strong>CNN+MHSA:</strong> CNN+MHSA model > Only CNN Model>Only MHSA model</p></li>
<li><p><strong>Strong augmentation:</strong> My model was performing well based on local CV, and public LB, with strong correlations between the two.But when I tested the model using this <a href="https://github.com/SamratThapa120/gradio-ASL-fingerspelling-recognition" target="_blank">Gradio app</a> using my webcam, it could not recognize my signs, so I had to use strong data augmentations to get the model to work. Especially temporal mask helped because I sign slower than the pros. These augmentations also boosted the public LB score by +0.006.</p>
<p>flip_lr_probability=0.5<br>
random_affine_probability=0.75<br>
freeze_probability=0.5<br>
temporal_mask_probability=0.75<br>
temporal_mask_range=(0.2,0.4)</p></li>
<li><p><strong>concat augmentation:</strong> Randomly concatenate two short landmark sequences, as well as their labels. This improved public LB by +0.008. I applied this augmentation to 40% of all training samples.</p></li>
</ul>
<h3>Here are other things I tried, that did not contribute to the best-performing model:</h3>
<ul>
<li><p><strong>transformer-encoder+decoder:</strong> Transformer endoder-decoder model with cross-entropy loss.</p></li>
<li><p><strong>transformer-decoder:</strong> CNN+MHSA model and Transformer-like decoder with cross-entropy loss.</p></li>
<li><p><strong>Causal-masking in self-attention:</strong> removing causal masking performed better than using causal mask.</p></li>
<li><p><strong>Attention-span in self-attention:</strong> I thought that there would not be long-term dependency between frames for this task, so I tried to reduce the attention span of self-attention. Although there was no performance degradation, it did not boost performance either.</p></li>
<li><p><strong>Focal loss</strong>: I tried the CTC Focal loss based on <a href="https://github.com/TeaPoly/CTC-OptimizedLoss/blob/main/ctc_focal_loss.py" target="_blank">this</a> repo, but there were no gains.</p></li>
<li><p><strong>Erase landmarks augmentation</strong>: Randomly erase landmarks except the hand landmarks, to make the model more robust to mediapipe's detection errors.</p></li>
</ul>
<p>Originally I was using <a href="https://github.com/SamratThapa120/sign-language-finger-spelling/tree/pytorch" target="_blank">pytorch</a>, but I switched to Tensorflow because I faced several issues when converting the pyTorch model to tfLite. However, training with CTC Loss was upto 10x slower in tensorflow than pytorch. Looking back, I think I should have put more effort into fixing the model conversion issue, as I would have been able to perform more experiments. </p>
<p>Congratulations to the winning teams. I would also like to thank Google for hosting this competition, it was a valuable opporunity to learn many new things. Also, I would like to thank everyone who shared their notebooks and unique ideas.</p>
<p>Freeze augmentation tries to replicate frozen frames in a video. Randomly select some frames and replicate them without changing their order in the sequence. For example [a,b,c,d,e] will get converted to something like [a,a,a,b,b,c,d,e,e]. </p>
<p><a href="https://github.com/SamratThapa120/sign-language-finger-spelling/blob/2bbc9a4c51622d3553ab9be17715ca51332c8797/signet/dataset/transforms.py#L215" target="_blank">Here is the code</a></p> |
Google - American Sign Language Fingerspelling Recognition | 25th Place Solution (time warpping + relative positional encoding + intermediate CTC) | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to Kaggle and Google for hosting this competition. This is my first Kaggle competition experence and I have learnt a lot from the previous ASL competition and other participants. I start my model from <a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a>'s solution from the last competition and added some components:</p>
<p><strong>Data Augmentation</strong><br>
Applied random time warpping (LB +0.01)</p>
<pre><code>def temporal:
n = tf.shape(x)
n < :
return x
w = n
t1 = tf.clip, , n-)
t2 = tf.clip + t1, , n-)
new_x1 = interp1d
new_x2 = interp1d
return tf.concat(, axis=)
def augment:
tf.random.uniform()< always:
x = resample(x, (,))
tf.random.uniform()< always:
x = flip
max_len is not None:
x = temporal
tf.random.uniform()< always:
x = spatial
tf.random.uniform()< always:
x = temporal
tf.random.uniform()< always:
x = temporal
tf.random.uniform()< always:
x = spatial
return x
</code></pre>
<p><strong>Data Preprocessing</strong><br>
Truncate <code>phrase</code> to have smaller length than the input</p>
<pre><code> inp_len <= label_len:
offset = tf((), , label_len-inp_len+, dtype=tf.int32)
=
label_len = inp_len-
</code></pre>
<p><strong>Multi-headed attention with relative positional encoding</strong> (LB +0.02)</p>
<pre><code> :
def :
super.
self.dim = dim
self.head_dim = dim
self.scale = self.head_dim-
self.num_heads = num_heads
self.num_nbr = num_nbr
self.qkv = tf.keras.layers.
self.drop1 = tf.keras.layers.
self.proj = tf.keras.layers.
self.supports_masking = True
self.wgt_v = self.add,
='glorot_uniform',trainable=True,
name=+str(tf.keras.backend.get))
self.wgt_k = self.add,
='glorot_uniform',trainable=True,
name=+str(tf.keras.backend.get))
def :
idx_mat = tf.reshape(tf.tile(tf.range(length), ), )
idx_mat = idx_mat - tf.transpose(idx_mat)
return tf.clip + self.num_nbr
def :
xy = tf.matmul(x, y, transpose_b=transpose)
x = tf.keras.layers.)(x)
mul = tf.matmul(x, z, transpose_b=transpose)
mul = tf.keras.layers.)(mul)
return xy + mul
def call(self, inputs, mask=None):
mask is not None:
mask = mask
length = inputs.shape
idx_mat = self.
rpe_k = tf.gather(self.wgt_k, idx_mat)
rpe_v = tf.gather(self.wgt_v, idx_mat)
qkv = self.qkv(inputs)
qkv = tf.keras.layers.)(tf.keras.layers.)(qkv))
q, k, v = tf.split(qkv, , axis=-)
logits = self.self.scale
attn = tf.keras.layers.(logits, mask=mask)
attn = self.drop1(attn)
x = self.
x = tf.keras.layers.)(tf.keras.layers.)(x))
x = self.proj(x)
return x
</code></pre>
<p><strong>Intermediate CTC</strong></p>
<pre><code>def get_base_model(=384, =384):
inp = tf.keras.Input((max_len,CHANNELS), =)
x = tf.keras.layers.Masking(=PAD,input_shape=(max_len,CHANNELS))(inp)
x = tf.keras.layers.Dense(dim, =,name='stem_conv')(x)
x = tf.keras.layers.BatchNormalization(=0.95,name='stem_bn')(x)
ksize = 17
drop_rate = 0.2
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = TransformerBlock(dim,=2)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = TransformerBlock(dim,=2)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = TransformerBlock(dim,=2)(x)
inter = tf.keras.layers.Dense(dim, =None)(x)
inter = tf.keras.layers.Dense(NUM_CLASSES+1)(inter)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = TransformerBlock(dim,=2)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = TransformerBlock(dim,=2)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = Conv1DBlock(dim,ksize,=drop_rate)(x)
x = TransformerBlock(dim,=2)(x)
x = tf.keras.layers.Dense(dim,=None,name='top_conv')(x)
x = tf.keras.layers.Dense(NUM_CLASSES+1, =)(x)
return tf.keras.Model(inp, [inter, x])
def ctc_loss(args):
y_pred, inp_len, label, label_len = args
return tf.nn.ctc_loss(label, y_pred, label_len, inp_len,
=, =NUM_CLASSES)
def get_model(base_model):
label = tf.keras.Input(shape=(MAX_LEN_OUTPUT,), =, =)
label_len = tf.keras.Input(shape=(), =, =)
inp_len = tf.keras.Input(shape=(), =, =)
loss1 = tf.keras.layers.Lambda(ctc_loss, output_shape=())(
[base_model.output[0], inp_len, label, label_len])
loss2 = tf.keras.layers.Lambda(ctc_loss, output_shape=())(
[base_model.output[1], inp_len, label, label_len])
loss = 0.3 * loss1 + 0.7 * loss2
#loss = 0.0 * loss1 + 1.0 * loss2
model = tf.keras.Model(
inputs=[base_model.input, inp_len, label, label_len],
=loss)
return model
</code></pre>
<p><strong>Fine tuning</strong> (LB +0.005)<br>
The model was first trained with both training data and supplementary data with intermediate CTC (0.3 and 0.7) for 300 epochs. Then the pre-trained model was fine tuned only on the training data without intermediate CTC (0.0 and 1.0)</p>
<p>I will post the training notebook soon.</p>
<p><a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a>'s solution<br>
<a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training" target="_blank">https://www.kaggle.com/code/hoyso48/1st-place-solution-training</a></p> |
Google - American Sign Language Fingerspelling Recognition | 29th Place Solution - LB 0.762 | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>TL;DR</h2>
<p>We used a 1D convolutional network with 122-dimensional features as input and Self Conditional CTC, along with a greedy search as the decoder.</p>
<h2>Preprocess</h2>
<p>We used xy feature points of the hand performing the gesture and xy feature points of the lips, for a total of 61 xy feature points (= 122-dimensional vector).</p>
<h2>Data Augmentation</h2>
<p>Overfitting was suppressed by randomly dropping hand feature points. The percentage of dropping was 40% of the total, and at least 5 consecutive frames were dropped.</p>
<h2>Model</h2>
<p>We used a 1DCNN consisting of 9 Residual Blocks of kernel width 3 and 12 Residual Blocks of kernel width 31.</p>
<h2>Loss Function</h2>
<p>We used Self Conditional CTC, a variant of CTC, for the loss function. By using Self Conditional CTC, a significant performance improvement was seen without increasing the amount of calculation.<br>
<a href="https://arxiv.org/abs/2104.02724" target="_blank">Read more about Self Conditional CTC here</a></p>
<h2>Training</h2>
<ul>
<li>60 epochs</li>
<li>CosDecay learning rate</li>
<li>AdamW optimizer</li>
<li>AWP</li>
</ul>
<h2>Convert Model</h2>
<p>All implementation was done in PyTorch and converted to 16-bit quantized tflite by onnx2tf. Conversion using nobuco was also tried, but was not adopted because, contrary to expectations, it increased processing time.</p>
<h2>Not Worked</h2>
<ul>
<li>Stochastic Weight Averaging was very effective in the last competition but did not contribute to performance in this competition.</li>
<li>We thought that Levenshtein OCR could be used as a decoder and tried to implement it, but it did not work.</li>
</ul> |
Google - American Sign Language Fingerspelling Recognition | 2nd place solution - Test & Compare ASR algorithms | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I used KaggleDatasets(same as previous competition, converted .parquet to .tfrecords). every kaggle dataset has its own Google Cloud Storage path, so if it is public and you have the actual gcs path then you can access it anywhere with GCS.</p>
<p>Thanks and congratulations! Your work through these two competitions was very masterful. need more time to digest, but I've already learned a lot from your solution :)</p>
<p>Once again, thanks to Kaggle, Google and other organizers for hosting this exciting competition. I felt this one as well as the previous competition, is well-organized so that we can try various ideas and could learn a lot from each other. Hope this kinds of competition open in kaggle more often.. :)</p>
<h2>TLDR</h2>
<p>My overall solution is almost identical to the previous competition. It's mainly just the adoption of ASR(Automatic Speech Recognition) algorithms (joint CTC + Attention) on top of the previous 1st place model. The details of the model, preprocessing, and training are largely similar to the previous competition, so please refer to the <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">previous competition solution</a> for more details on model/training/augmentations/etc.</p>
<h2>ASR Algorithms</h2>
<p>I had a deep interest in ASR, and after recognizing its correlation with the competition, I studied and experimented with various algorithms. While I couldn't find anything particularly superior to the widely used vanilla CTC among the numerous ASR algorithms, I learned a lot through various experiments, and I will mainly share those insights.</p>
<p>As I began studying ASR for this competition, I discovered from reading papers that current NN ASR algorithm mainly consists of CTC, Attention-based, and Transducer. I implemented all three (though there are more diverse algorithms out there). In conclusion, from a baseline performance perspective, all three algorithms were quite similar and each have pros & cons. Here are the insights I gathered from implementing each algorithm:</p>
<ul>
<li><p>CTC:</p>
<ul>
<li>During greedy decoding, the prediction step = O(1). Therefore, when using a Single model, GreedyCTC is the most efficient. (this is probably why many solutions use a large single model with CTC).</li>
<li>With beam search, prediction step = O(L) (where L = encoder output length). Depending on the efficiency of the algorithm, the computational overhead isn't very large, so the overhead by introducing beam search isn't very significant. However, the performance improvement from using beam search is minimal (+0.003), making it not very tempting(as its tflite-convertible implementation is not quite trivial) compared to Attention.</li>
<li>As discussed, there's no guarantee of alignment between model prediction timesteps, so simple average ensembling can't be applied.</li></ul></li>
<li><p>Attention-based:</p>
<ul>
<li>Uses an autoregressive approach, so even with greedy decoding, prediction step = O(N) (where N = decoder output length).</li>
<li>If the decoder is an RNN or Transformer, stateful inference(i.e. previous key, value caching with Transformer) can be used to reduce the complexity. In actual implementation with Transformer, it reduced the inference time on the CPU by about 20~30%.</li>
<li>Beam search is possible, but unlike CTC, it requires introducing appropriate heuristics to penalize the output length. Although several attempts were made, none worked. </li>
<li>It's easier to apply ensembling with Attention. Simply take the average of each model at each prediction step, and it works well (ensembling three models gave +0.009).</li>
<li>More room for score improvement than CTC(ex more decoder layers with augmentations).</li></ul></li>
<li><p>Transducer:<br>
Prediction steps = O(L) (where L = encoder output length). Due to the most prediction steps in a greedy manner, it's not very efficient. I didn't consider it further as optimization was harder and performance was slightly lower compared to CTC or Attention. However, it has the advantage of real-time recognition in streaming mode if the encoder is causal (which wasn't relevant for this competition).</p></li>
</ul>
<p>Rough single model inference time on test dataset with kaggle kernel is as follows.</p>
<blockquote>
<p>CTC greedy(~40mins) < AttentionGreedy=CTCBeamsearch(~1h20mins) <= CTCAttentionJointGreedy(~1h30mins)</p>
</blockquote>
<h2>CTC-Attention Joint Training & Decoding</h2>
<p>As both CTC and Attention showed similar performance, I tried to find a method to utilize both techniques. I primarily referred to the following two papers:</p>
<p><em>Joint CTC-Attention Based End-To-End Speech Recognition Using Multi-Task Learning, Kim et al. 2017.</em><br>
<a href="url" target="_blank">https://arxiv.org/pdf/1609.06773.pdf</a><br>
<em>Joint CTC/attention decoding for end-to-end speech recognition, Hori et al. 2017.</em><br>
<a href="url" target="_blank">https://aclanthology.org/P17-1048.pdf</a></p>
<p>Joint CTC-Attention Training is, as the name implies, adding both a CTC decoder (single GRU layer) and an attention decoder (single Transformer decoder layer) to one encoder for multitask learning. The loss weight is set to CTC=0.25 and attention=0.75. But the Joint training itself did not bring noticeable performance boost.</p>
<p>By using the CTC prefix score, it is possible to calculate the probability of an arbitrary output hypothesis "h" without depending on the output timestep of the CTC output. In other words, <strong>implementing the CTC prefix score computation allows for ensembling outputs not only between CTC models but also between CTC and Attention models</strong>. CTC-attention joint decoding with CTC weight=0.3 showed a performance improvement of +0.007~8 without much impact on inference time. It was especially challenging for me to implement it accurately, efficiently, and without any issues to be compatible with tflite.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5003978%2Fabde23b44b90f8ba6adc7d56ca874d86%2F.drawio-3.svg?generation=1692977029060458&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5003978%2F22c798e256f66322a0cc9e42b976d570%2F.drawio-4.svg?generation=1692977118893507&alt=media" alt=""></p>
<h2>Preprocessing</h2>
<p>Similar to the previous competition solution, but simpler. Every landmark and xyz was used and standardized. Flip left-handed signer(rather than augmentation). MAX_LEN=768 was used. Any hand-crafted feature was not significant, likely due to the absence of complex relations between movements in frames.</p>
<h2>Model</h2>
<p>Encoder is the same as the previous competition (Stacked Conv1DBlock + TransformerBlock) but increased in size (expand ratio 2->4 in Conv1DBlock) and depth (8 layers -> 17 layers). Single model has ~6.5M parameters. I applied padding='same'(rather than 'causal') and output stride=2 (requires slightly more logic for handling masking). In my case, mixing in Transformer blocks wasn't as effective as in the previous competition. Perhaps global features were less crucial in this comp. Additionally, I added one BN to input of the Conv1DBlock for more training stability(especially with awp + more epochs).</p>
<p>CTC decoder used a single GRU layer followed by one FC layer. Attention Decoder used a single-layer Transformer decoder. Introducing augmentation to the Decoder input and adding up to 4 Decoder layers improves the performance of the attention decoder (up to +0.004). However, considering the number of parameters and inference speed, I considered it inefficient and thus used a single-layer decoder.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5003978%2F7d1f7aee69242af5e6aa5ef19c9460f6%2Fmodeldesign.drawio-2.svg?generation=1692993585923781&alt=media" alt=""></p>
<h2>Augmentations</h2>
<ul>
<li>Random resample (0.5x ~ 1.5x to original length)</li>
<li>Random Affine</li>
<li>Random Cutout</li>
<li>Random token replacement on decoder input(prob=0.2)</li>
</ul>
<p>What I overlooked this time is that augmentations which showed no performance improvement or even degraded performance in shorter epochs might actually help improve performance in longer epochs. I experienced a similar phenomenon in the previous competition, but it seemed more pronounced in this one. By selecting augmentations solely based on the results from a 60epoch experiment, I think I missed out on many potentially beneficial augmentations when testing the 400epoch training in the final week.</p>
<h2>Training</h2>
<p>Epoch = 400<br>
bs = 16 * num_replicas = 128<br>
Lr = 5e-4 * num_replicas = 4e-3<br>
AWP = 0.2 starts at 0.1 * Epoch<br>
Schedule = CosineDecay with warmup ratio 0.1<br>
Optimizer = AdamW (slightly better than RAdam with Lookahead)<br>
Loss = CTC(weight=0.25) + CCE with label smoothing=0.1~0.25(weight=0.75)</p>
<p>Training takes around 14 hours with colab TPUv2-8(as colab TPU runtime recently reduced to 3~4 hours, needed 4 consecutive sessions to complete training).<br>
Longer Epoch always gave better CV(5fold split by id) and LB but got no time to try over 400 epochs.</p>
<h2>LB history</h2>
<table>
<thead>
<tr>
<th></th>
<th>public LB</th>
<th>private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>prevcompsinglemodel + CTC (or Attention)</td>
<td>0.76</td>
<td>0.74</td>
</tr>
<tr>
<td>+ deeper and wider model, add pose</td>
<td>0.79</td>
<td>0.78</td>
</tr>
<tr>
<td>+ 3 seed ensemble with Attention</td>
<td>0.80</td>
<td>0.79</td>
</tr>
<tr>
<td>+ ctc attention joint decoding</td>
<td>0.81</td>
<td>0.80</td>
</tr>
<tr>
<td>+ use all landmarks, longer epoch</td>
<td>0.82</td>
<td>0.81</td>
</tr>
</tbody>
</table>
<p>Seeing solutions from other kagglers, not only the top solutions but also the public notebooks is always inspiring. Thanks to kagglers who shared their insights and ideas as always. And big congrats to <a href="https://www.kaggle.com/christofhenkel" target="_blank">@christofhenkel</a> and <a href="https://www.kaggle.com/darraghdog" target="_blank">@darraghdog</a> for winning this highly competitive competition!</p>
<p>Training/Inference code: <a href="https://www.kaggle.com/competitions/asl-fingerspelling/discussion/436873" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/discussion/436873</a></p>
<p>Thanks, and congrats on winning! I've always learned from top Kagglers like you, and now I'm happy that I could also provide you with some insights :)</p>
<p>Glad to know that my prev solution gave you some help :)<br>
I relied on my prev model and gave minimal changes simply because it's my own implementation from prev competition with lots of trials&errors..haha<br>
Definitely should study&try more recent conv + transformer hybrid architectures next time. Thanks!</p>
<p>Yes. I only used Colab TPUv2-8.</p>
<p>I did not refer to any particular paper in the previous competition. Of course, I did search through some papers on related tasks (such as action recognition and GCN models) at the beginning, but I realized that the methods from those papers were not very effective.</p> |
Google - American Sign Language Fingerspelling Recognition | 33rd place solution - LB 0.758 | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you :)<br>
Yes, we implemented it as you mentioned, but it didn't work.<br>
There are moving gesture characters such as 'z' and we guess reversed motion may interrupt learning.<br>
Augmentation of phrase consiting with only static gesture may helpful but we didn't try it</p>
<h2>TL;DR</h2>
<p>We used a conformer-like model consisting transformer encoder, 1d convolution with CBAM and bi-LSTM.<br>
Overall model size is about 16MB after INT8 quantization.<br>
Training objective is CTC with InterCTC loss.</p>
<h2>Data preprocess</h2>
<ul>
<li>Used landmarks<ul>
<li>1 for nose, 21 for dominant hand, 40 for lips</li>
<li>x, y coordinates</li></ul></li>
<li>Normalization<ul>
<li>Standardized distance from nose coordinates</li></ul></li>
<li>Feature engineering<ul>
<li>Concatenation of normalized location, difference of next frame, joint distance of hand</li>
<li>Total 582 dims</li></ul></li>
<li>Removing data that input frame is shorter than 2 times of target phrase</li>
</ul>
<h2>Data augmentation</h2>
<ul>
<li>Horizontal flip landmarks</li>
<li>Interpolation</li>
<li>Affine transfrom</li>
</ul>
<h2>Model</h2>
<ul>
<li>2 stacked encoder with Transformer, 1D convolution with CBAM and Bi-LSTM<ul>
<li>hidden dim: 352</li></ul></li>
<li>CTC loss and Inter CTC loss after first encoder</li>
<li>17M parameters and INT8 quantization</li>
</ul>
<h2>Train</h2>
<ul>
<li>2 staged training (300 + 200 epochs)<ul>
<li>Use supplemental and train data in first 300 epochs</li>
<li>Use train data 200 epochs</li></ul></li>
<li>Ranger optimizer</li>
<li>Cosine decay scheduler with 12 epochs warmup</li>
<li>AWP<ul>
<li>It prevents the validation loss from diverging, but it doesn't seem to improve the edit distance.</li>
<li>Used to train long epochs.</li></ul></li>
</ul>
<h2>Not worked</h2>
<ul>
<li>Augmentation<ul>
<li>Time, spatial, landmark masking</li>
<li>Time reverse</li></ul></li>
<li>Autoregressive decoder<ul>
<li>Use joint loss, CTC loss for encoder and Crossentropy for decoder</li>
<li>Inference time is longer and the number of parameters larger than those of the CTC encoder alone, but the performance improvement is not clear, so it is not used.</li></ul></li>
</ul> |
Google - American Sign Language Fingerspelling Recognition | 449th Position Solution for Google ASLFR Competition - Adversarial Regularization, Quantization Aware Training, and KD Code for Tensorflow! | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi Everyone! I'm just posting my solution here, in case it could help someone! I used a lot of techniques, but didn't have the computing power to push the boundaries required for a very high rank. Nevertheless, I learnt a lot of techniques, and am writing this solution here to help provide useful code!</p>
<h1>Competition Context</h1>
<p>The context of this solution is the Google - American Sign Language Fingerspelling Recognition Competition:<br>
<a href="https://www.kaggle.com/competitions/asl-fingerspelling/overview" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/overview</a></p>
<p>The data of this competition can be found here:<br>
<a href="https://www.kaggle.com/competitions/asl-fingerspelling/data" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/data</a></p>
<h1>My Approach</h1>
<p>My approach was identical to most people, I referred to the really awesome notebook by Rohit Ingilela here: <a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place</a></p>
<p>I made several additions and changes, namely by adding Quantization Aware Training, AWP, and Knowledge distillation (not necessarily in the same model). I tested a lot of parameters as well and made a lot of models.</p>
<p>My idea was to use Quantization to increase model size. I found that after 24 Million parameters, even though the model size was small enough, the performance became too poor to run within the 5 hours allocated for testing. I found that KD didn't improve my performance too much, so I didn't explore it a lot. I tried AWP only at the end, and even though it improved performance by around 0.003, I didn't get to test it a lot.</p>
<p>Nevertheless, here is some code for each idea:</p>
<p><strong>Quantization:</strong></p>
<pre><code>!pip install -q tensorflow-model-optimization
tensorflow_model_optimization tfmot
tensorflow.keras layers
x = tfmot.quantization.keras.quantize_annotate_layer(layers.Dense(channels, activation = activation, kernel_regularizer = regularizer))(inputs)
tflitemodel_base = TFLiteModel(model)
tflitemodel_base(frames)[].shape
keras_model_converter = tf.lite.TFLiteConverter.from_keras_model(tflitemodel_base)
keras_model_converter.optimizations = [tf.lite.Optimize.DEFAULT]
keras_model_converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
tflite_model = keras_model_converter.convert()
(, ) f:
f.write(tflite_model)
</code></pre>
<p><strong>Adversarial Regularization in Training</strong></p>
<pre><code>! pip install -q neural-structured-learning
neural_structured_learning nsl
adv_config = nsl.configs.make_adv_reg_config(
multiplier = ,
adv_step_size = ,
adv_grad_norm =
)
():
{: image, : label}
train_dataset = train_dataset.(convert_to_dictionaries)
val_dataset = val_dataset.(convert_to_dictionaries)
strategy.scope():
model = nsl.keras.AdversarialRegularization(
model,
label_keys = [],
adv_config = adv_config
)
loss = CTCLoss
optimizer = tfa.optimizers.RectifiedAdam(sma_threshold = )
optimizer = tfa.optimizers.Lookahead(optimizer, sync_period = )
model.(loss = loss, optimizer = optimizer)
</code></pre>
<p><strong>Knowledge Distillation</strong></p>
<pre><code> (keras.Model):
():
().__init__()
self.student = student
self.teacher = teacher
():
().(optimizer=optimizer)
self.loss = CTCLoss
self.distiller_loss_fn = keras.losses.KLDivergence()
self.alpha = alpha
self.temp = temperature
():
x, y = data
is_batch_small = tf.math.less(tf.shape(x)[], train_batch_size)
is_batch_small = tf.math.reduce_all(is_batch_small)
():
tf.constant(), tf.constant()
():
teacher_pred = self.teacher(x, training = )
tf.GradientTape() tape:
student_pred = self.student(x, training = )
student_loss = self.loss(y, student_pred)
distilled_loss = self.distiller_loss_fn(
tf.nn.softmax(student_pred / self.temp),
tf.nn.softmax(teacher_pred / self.temp)
) * (self.temp ** )
loss = self.alpha * student_loss + ( - self.alpha) * distilled_loss
trainable_vars = self.student.trainable_variables
gradients = tape.gradient(loss, trainable_vars)
self.optimizer.apply_gradients((gradients, trainable_vars))
self.compiled_metrics.update_state(y, student_pred)
student_loss, distilled_loss
student_loss, distilled_loss = tf.cond(is_batch_small, pass_batch, normal)
results = {m.name : m.result() m self.metrics}
results.update(
{: student_loss, : distilled_loss}
)
results
():
()
x, y = data
is_batch_small = tf.less(tf.shape(x)[], val_batch_size)
is_batch_small = tf.reduce_all(is_batch_small)
():
tf.constant(), tf.constant()
():
y_pred = self.student(x, training = )
teacher_pred = self.teacher(x, training = )
student_loss = self.loss(y, y_pred)
distilled_loss = self.distiller_loss_fn(
tf.nn.softmax(y_pred / self.temp),
tf.nn.softmax(teacher_pred / self.temp)
) * (self.temp ** )
self.compiled_metrics.update_state(y, y_pred)
student_loss, distilled_loss
student_loss, distilled_loss = tf.cond(is_batch_small, pass_batch, normal)
results = {m.name : m.result() m self.metrics}
results.update(
{: student_loss, : distilled_loss}
)
results
</code></pre>
<p>While I didn't get a super high rank, I did learn a lot and used a plethora of techniques! I wrote most things from scratch, to learn things myself, and referred to other's work only to get a better understanding of what they did and improve my own code as a result.</p>
<p><em>Validation</em><br>
Quite standard - kept a holdout set and computer Normalized Levenshtein distance on it after every epoch.<br>
No CV due to low computational resources.</p>
<h1>Improvements</h1>
<p>I am quite disappointed that the things I missed out were very trivial - such as not training for more than 300 epochs (I could only manage 100 to try enough models and variations out) and that keeping some missing hands frames was important.</p>
<p>I also didn't use enough augmentations which was important, even though I used all the ones used by top submissions except cutout.</p>
<p>I also read about Squeezeformer, but got demotivated because I saw high scoring public submissions without Squeezeformer :(</p>
<p>To further improve, I'll correct all the points above.</p>
<h1>Final Note</h1>
<p>I am quite happy to have participated in this fun and awesome contest. I really learnt a lot, and experimented a lot. I am certain that what I did here will help me in future competitions, research and work.</p>
<p>If you could give me any suggestions/feedback on my code above, please do so. It will help me improve and learn, and I will be very grateful for your help!</p>
<p>Thank you so much!</p> |
Google - American Sign Language Fingerspelling Recognition | 95th Bronze solutions | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>95th Bronze solutions</h1>
<p>Thanks to Kaggle for hosting this interesting competition!!!!<br>
This competition was diffucult for us…<br>
There were many differences from last competition which made it challenging. I enjoyed learning about transcription task.</p>
<h1>Summary</h1>
<p>We utilized the best public notebook with some modifications.</p>
<ul>
<li>base notebook: <a href="https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-place</a></li>
</ul>
<h1>What changes were made from the public notebook?</h1>
<ul>
<li><p>Normalization (+0.002 LB)</p>
<ul>
<li>Adjusted all coordinates so that the center of numbers 11 and 12 is set to 0.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2930242%2F6d424a3976cee8f769e3e90ba54a9ac2%2Finbox_2930242_fa394dbd96e33fb875aef6ed1f25c757_1.png?generation=1692922021894426&alt=media" alt=""></li></ul></li>
<li><p>Added more features (+0.01 LB)</p>
<ul>
<li>Motion, Shape Feature, <ul>
<li>Shape is distance of this point<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2930242%2F3f7fdc56a208576b7664408fd807e422%2Finbox_2930242_b739316822c577ef9b4be204325f569e_2.png?generation=1692922063719858&alt=media" alt=""></li></ul></li></ul></li>
<li><p>Feature Augmentation (+0.01 LB)</p>
<ul>
<li>Framerate, randomDrop, random padding, random crop.</li></ul></li>
<li><p>Changed Model (+0.005 LB)</p>
<ul>
<li>dim : 384 => 192</li>
<li>conv trans Block num : 3=>10</li>
<li>Add aux Loss</li></ul></li>
<li><p>Pretraining with supplementay data (+0.01 LB)</p></li>
<li><p>Training params</p>
<ul>
<li>epoch 100</li>
<li>batchsize 256</li>
<li>learningrate 1e-2</li></ul></li>
</ul>
<h1>Things I couldn't do</h1>
<ul>
<li>Error correction Network.<ul>
<li>I read the following paper and tried to incorporate voice recognition technology, but I couldn't make it in time.</li>
<li><a href="https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjAkrKRvvaAAxWBO3AKHbDkB4MQFnoECBMQAQ&url=https%3A%2F%2Farxiv.org%2Fabs%2F2111.01690&usg=AOvVaw3B--e8pJqXTaYolWYXIBOf&opi=89978449" target="_blank">https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjAkrKRvvaAAxWBO3AKHbDkB4MQFnoECBMQAQ&url=https%3A%2F%2Farxiv.org%2Fabs%2F2111.01690&usg=AOvVaw3B--e8pJqXTaYolWYXIBOf&opi=89978449</a></li></ul></li>
<li>Change to SOTA OCR model.<ul>
<li><a href="https://arxiv.org/pdf/2205.00159.pdf" target="_blank">https://arxiv.org/pdf/2205.00159.pdf</a></li></ul></li>
</ul>
<h1>Appendix: Model code</h1>
<pre><code>def get:
inp = tf.keras.
x = tf.keras.layers.(inp)
x = tf.keras.layers.(x) + positional
x = tf.keras.layers.(x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x_aux = (x)
x = (x_aux)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
x = (x)
# main
x = tf.keras.layers.(x)
x = tf.keras.layers.(x)
x = tf.keras.layers.,name='out')(x)
#aux
x_aux = tf.keras.layers.(x_aux)
x_aux = tf.keras.layers.(x_aux)
x_aux = tf.keras.layers.,name='aux_out')(x_aux)
model = tf.keras.
loss = {
'out':CTCLoss,
'aux_out':CTCLoss
}
# Adam Optimizer
optimizer = tfa.optimizers.
optimizer = tfa.optimizers.
model.compile(loss=loss, optimizer=optimizer)
return model
</code></pre> |
Google - American Sign Language Fingerspelling Recognition | 95th Bronze solutions: Focal loss + KD + Supplemental data | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you, Kumar. Utilizing TPU would result in quicker performance compared to a GPU.</p>
<h2><strong>95th Bronze Solutions (public score 0.714, private score 0.671)</strong></h2>
<p>I express my gratitude to Kaggle and Google for organizing this competition. Participating in this competition has been an invaluable learning experience for me.</p>
<p>One significant achievement was improving the public score from Version 17 of Saidineshpola's notebook, which initially achieved a public score of 0.689. The improvements were achieved by implementing the following modifications:</p>
<h1><strong>Model & Config:</strong></h1>
<ul>
<li>Set model dimensions (Dim) to 192.</li>
<li>Set 16 CNN-Transformer blocks.</li>
<li>Incorporated a dropout rate of 0.4.</li>
<li>Utilized 8 attention heads and an expansion factor of 8 in the Transformer blocks.</li>
<li>The total number of parameters amounted to 19,255,980.</li>
<li>Employed tf.float16 for model conversion.</li>
<li>Configured training with 100 epochs, with 10 warm-up epochs.</li>
<li>Set the maximum learning rate (LR_MAX) to 1e-3.</li>
<li>Set the weight decay (WD_RATIO) to 1e-4.</li>
</ul>
<h1><strong>CTC loss:</strong></h1>
<p>I utilized the CTC loss function from the <code>pip install tf-seq2seq-losses</code> library, which provided comparable results to TensorFlow's built-in function. This implementation offered a speed enhancement of around 25% on V100 GPUs. Additionally, I applied the Focal loss to the CTC loss function.</p>
<pre><code> tf_seq2seq_losses classic_ctc_loss
():
label_length = tf.reduce_sum(tf.cast(labels != pad_token_idx, tf.int32), axis=-)
logit_length = tf.ones(tf.shape(logits)[], dtype=tf.int32) * tf.shape(logits)[]
ctc_loss = classic_ctc_loss(
labels=tf.cast(labels, dtype=tf.int32),
logits=logits,
label_length=label_length,
logit_length=logit_length,
blank_index=pad_token_idx,
)
p= tf.exp(-ctc_loss)
alpha =
gamma =
focal_ctc_loss= tf.multiply(tf.multiply(alpha,tf.((-p),gamma)),ctc_loss)
loss = tf.reduce_mean(focal_ctc_loss)
loss
</code></pre>
<h1><strong>Data augmentation:</strong></h1>
<p>No data augmentation techniques were applied.</p>
<h1><strong>Additional data:</strong></h1>
<p>Supplemental data was integrated into the training process. I followed <a href="https://www.kaggle.com/code/irohith/aslfr-preprocess-dataset/notebook" target="_blank">ROHITH INGILELA's notebook</a> to generate supplemental TFrecord files. The resources used are available <a href="https://www.kaggle.com/datasets/kongpasom/aslfr-sup-tfrecord" target="_blank">here</a> and <a href="https://www.kaggle.com/datasets/kongpasom/aslfr-sup" target="_blank">here</a> .</p>
<h1><strong>Training Approach:</strong></h1>
<ol>
<li>Trained the model using supplemental data for 100 epochs.</li>
<li>Trained the model with training data and the pre-trained weights derived from the - supplemental data for an additional 100 epochs (resulting in a public score of 0.713).</li>
<li>Executed a fine-tuning process using knowledge distillation, refining the model with the best pre-trained weights through the AdamW optimizer, resulting in a modest score improvement of +0.001.</li>
</ol>
<h1><strong>Model Architecture:</strong></h1>
<p>Here's a summarized version of the model architecture:</p>
<pre><code> ():
inp = tf.keras.Input(INPUT_SHAPE)
x = tf.keras.layers.Masking(mask_value=)(inp)
x = tf.keras.layers.Dense(dim, use_bias=, name=)(x)
pe = tf.cast(positional_encoding(INPUT_SHAPE[], dim), dtype=x.dtype)
x = x + pe
x = tf.keras.layers.BatchNormalization(name=)(x)
num_blocks =
drop_rate =
i (num_blocks):
x = Conv1DBlock(dim, , drop_rate=drop_rate)(x)
x = Conv1DBlock(dim, , drop_rate=drop_rate)(x)
x = Conv1DBlock(dim, , drop_rate=drop_rate)(x)
x = TransformerBlock(dim=dim, num_heads=, expand=, attn_dropout=, drop_rate=)(x)
x = tf.keras.layers.Dense(dim*,activation=,name=)(x)
x = tf.keras.layers.Dropout()(x)
x = tf.keras.layers.Dense((char_to_num), name=)(x)
model = tf.keras.Model(inp, x)
loss = CTCLoss
optimizer = tfa.optimizers.RectifiedAdam(sma_threshold=)
optimizer = tfa.optimizers.Lookahead(optimizer, sync_period=)
model
</code></pre>
<h1><strong>Knowledge Distillation Training :</strong></h1>
<p>A training step using knowledge distillation was employed to refine the model:</p>
<pre><code>loss_fn = CTCLoss
kld_loss_fn = tf.keras.losses.KLDivergence()
():
temperature =
alpha =
teacher_pred = model_teacher(x, training=)
tf.GradientTape() tape:
logits = model(x, training=)
loss_value = loss_fn(y, logits)
kld_loss = kld_loss_fn(
tf.nn.softmax(teacher_pred / temperature, axis=),
tf.nn.softmax(logits / temperature, axis=),
) * temperature**
loss = alpha * loss_value + ( - alpha) * kld_loss
grads = tape.gradient(loss, model.trainable_weights)
model.optimizer.apply_gradients((grads, model.trainable_weights))
loss, loss_value, kld_loss
</code></pre>
<h1><strong>Reference (</strong>If I have seen further, it is by standing on the shoulders of giants.<strong>) :</strong></h1>
<p><a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">ROHITH INGILELA's notebook</a><br>
<a href="https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">RSAIDINESHPOLA's notebook</a><br>
<a href="https://www.kaggle.com/code/irohith/aslfr-preprocess-dataset" target="_blank">ROHITH INGILELA's pre-process dataset notebook</a></p> |
Google - American Sign Language Fingerspelling Recognition | 9th Place Solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>The below is result of a team effort with <a href="https://www.kaggle.com/rafiko1" target="_blank">@rafiko1</a> and <a href="https://www.kaggle.com/group16" target="_blank">@group16</a> and myself.</p>
<p>We want to thank to the hosts for putting together a great competition, it was really fun and we were glad to end up in the gold zone! We've already enjoyed reading some of the top teams solutions- congrats to all who participated.</p>
<h2>tl;dr</h2>
<p>We used a similar architecture to <a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a>'s solution from the ASL-sign competition. Our model had six Conv1D/Transformer blocks, was trained with CTC loss over 500+ epochs, and utilized heavy augmentations.</p>
<p>This competition posed challenges beyond achieving model accuracy. We had to meet model constraints (5-hour submission limit and 40mb model size). We also needed to make sure all of our code converted nicely to tflite, which at times was frustrating. This required us to find a good balance between model size and inference time with minimal postprocessing.</p>
<h2>Data and Preprocessing:</h2>
<p>We used the training data as the base dataset, but also trained using the supplemental and external (ChicagoWild/Plus) during fine tuning. Preprocessing was the same for all datasets:</p>
<ul>
<li>Standard scaling using the mean and standard deviation for each point.</li>
<li>x, y, z coordinates for each point.</li>
<li>Points used included: RHAND, LHAND, LIP, POSE, REYE, and LEYE.</li>
<li>We tried different settings for the max frame length since it had the most impact on our preprocessing and ened up using 356.</li>
<li>Downsampling non-hand frames: To handle samples that has more than 356 frames, we first removed frames with missing hands at even intervals. This improved performance when we added it to our inference- so eventually we added it to our training pipeline.</li>
<li>Resize: Examples exceeding our max frame length post-downsampling were resized.</li>
</ul>
<h2>Augmentations:</h2>
<p>Heavy augmentations helped us to train long without the risk of overfitting.</p>
<ul>
<li>Mirror/Flip</li>
<li>Random resampling</li>
<li>Random rotation</li>
<li>Random spatial and temporal masking</li>
<li>Temporal cropping</li>
<li>Minimal Random noise</li>
<li>Random scaling</li>
</ul>
<h2>Training</h2>
<p>Given that training each model took a very long time to train (days running on colab TPUs), we resumed from the best checkpoints to experiment with different augmentations, data ratios, and learning rate schedules. It’s hard to exactly retrace the steps we took to get to our final model but the general idea was:</p>
<ul>
<li>Base training without augmentations at a consistent learning rate until convergence (~150 epochs).</li>
<li>Introducing heavy augmentations and continuing until the validation score plateaued (200-400+ epochs).</li>
</ul>
<p>Example of how our validation score improved from different experiments over the final week of the competition:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F644036%2F19aa07e39c404ae7599d66184997d351%2FScreenshot%20from%202023-08-26%2016-58-18.png?generation=1693083542531397&alt=media" alt=""></p>
<p>Even up until the end of the competition we were able to get small improvements in our score from more training.</p>
<h2>Model Architecture:</h2>
<p>Initially, I tried an efficientnet approach similar to the 2nd place in the signs competition. Later, I pivoted to the 1st place architecture similar to public notebooks. After merging teams we found both of us had similar architectures but <a href="https://www.kaggle.com/rafiko1" target="_blank">@rafiko1</a> made some modifications that improved it's performance on this task:</p>
<ul>
<li>Switched from 3 to 2 Conv1D per Conv/Transformer block.</li>
<li>Increated to 6 blocks (resulting in a 10.5M parameter model).</li>
<li>Parameters: 384 max frames, 320 dimensions, 8 heads per transformer. </li>
<li>Did not use a final MaxPooling layer.</li>
</ul>
<p>We also had experiments that used DebertaV2 instead of the transformer block, But the final model didn't use them.</p>
<h2>Increasing model size without retraining:</h2>
<p>Towards the competition's end, realizing we didn't have a great way to ensemble models, we wanted to get the biggest model possible without having to retrain. We found that instead of retraining from scratch we could simply expand the number of Conv1D/Transformer blocks we had - and copy the weights over from our previous best model, repeating the final layer weights. This allowed the model to converge very fast and squeeze out some additional accuracy while saying below the 5 hour inference limit.</p>
<h2>Attempts not in our final solution:</h2>
<ul>
<li><strong>Cutmix based on pseudo labels:</strong> The idea was to use model predictions to pinpoint frames displaying each letter in videos, then applying cutmix at the frame level during training. It functioned initially but became required us to recreate the tfrecords each time we modfiied preprocessing or model archetecture, so it wasn't used in our final solution. When it was used we only applied cutmix across similar phrase types (phone numbers mixed only with phone numbers, etc) but it was interesting to read the top team found it worked best mixing only between the same signer.</li>
<li><strong>Ensembling techniques:</strong> Couldn't find a good solution for this with CTC loss in tflite.</li>
<li><strong>Beam search</strong></li>
<li><strong>Efficientnet/Transformer</strong></li>
<li><strong>DebertaV2</strong></li>
</ul>
<h2>Postprocessing / Ensemble:</h2>
<p><strong>Fill word</strong>: As others have noted, there were a significant number of examples in the dataset with very few frames. These had low or no signal in them related to the target. We found it was better to just replace them with a fill word ('+w1- ea-or') We also found that it worked best to apply these to examples that had less than 30 frames AND a prediction phrase that was <= 6 characters.<br>
<strong>Model weight averaging</strong> Instead of using the final epoch of each training run, averaging the weights from the final few epochs really helped the CV and LB score. This became less powerful later in the competition when our models were stronger.</p>
<h2>Strong Validation/LB Correlation:</h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F644036%2F2a8e047f8cb571c018f477396c321a91%2Fsub-lb.png?generation=1693083215072772&alt=media" alt=""></p>
<p>We tracked each submission's execution time and CV/LB correlation. This competition had a really strong correlation between our validation set (one parquet file) and the LB. Our best private LB score was 0.788 but we didn't select it because it did not perform as well on the public LB.</p> |
Google - American Sign Language Fingerspelling Recognition | Custom MovinetClassifier Concept | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F396181%2F4663191986e89b81a51041daba2605e8%2Fanimation_23842.gif?generation=1692951869820889&alt=media" alt="hand_animation_23842"></p>
<p>Above illustrates transforming the hand landmarks (for row 23842 phrase 2 in train) in tensorflow preprocessing layers into a "clip" to be used for inference with a custom classifier fine tuned for the 59 prediction characters.<br>
MoViNet models for video classification have small streaming models that can be trained and inferred on CPU and converted to TF Lite. </p>
<p><a href="https://github.com/tensorflow/models/tree/master/official/projects/movinet" target="_blank">MoViNet model from TensorFlow Models</a><br>
custom classifier MovinetClassifier fine tune with pretrained weights e.g., movinet_a0_stream (trained on Kinetics 600) <br>
input shape 1 x 1 x 172 x 172<br>
checkpoint ~15 MB trained model ~30 MB TF Lite ~10 MB</p>
<p>Convert to TF SavedModel. Then the SavedModel can be converted to TF Lite using the TFLiteConverter<br>
<code>converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)</code><br>
<code>tflite_model = converter.convert()</code></p>
<p><a href="https://arxiv.org/abs/2103.11511" target="_blank">MoViNets: Mobile Video Networks for Efficient Video Recognition</a><br>
In the paper, multiple-class labels per video were used for Charades. <br>
Or per frame or selected frame inference was a possibility then post process with tensorflow unique_with_counts <br>
and considerations for double numbers or letters.</p>
<p>This was not finished for the competition, but adding here for interest and awareness of these models. <br>
And a bit of fun.<br>
It could be a next gen Sign Language uses video content with mediapipe markers and this would fit nicely.</p> |
Google - American Sign Language Fingerspelling Recognition | Public notebook, cosmetic changes, 190 position | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Of course, training lasted 50 epochs</p>
<p>Hi to all!<br>
I haven't been able to really compete in the last while, but I'll share the changes to the public notebook: <a href="https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-" target="_blank">https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-</a> place (special thanks to the author). Only two changes, I reduced the drop_rate and added another Dropout. Here's what the function looks like</p>
<p>def get_model(dim = 384,num_blocks = 6,drop_rate = 0.35):<br>
inp = tf.keras.Input(INPUT_SHAPE)<br>
x = tf.keras.layers.Masking(mask_value=0.0)(inp)<br>
x = tf.keras.layers.Dense(dim, use_bias=False, name='stem_conv')(x)<br>
pe = tf.cast(positional_encoding(INPUT_SHAPE[0], dim), dtype=x.dtype)<br>
x = x + pe<br>
x = tf.keras.layers.BatchNormalization(momentum=0.95,name='stem_bn')(x)</p>
<pre><code> i range(num_blocks):
x = (x)
x = (x)
x = (x)
x = (x)
x = tf.keras.layers.(x)
x = tf.keras.layers.(x)
x = tf.keras.layers.(x)
x = tf.keras.layers.,name='classifier')(x)
model = tf.keras.
loss = CTCLoss
# Adam Optimizer
optimizer = tfa.optimizers.
optimizer = tfa.optimizers.
model.compile(loss=loss, optimizer=optimizer)
return model
</code></pre>
<p>The changes are really minor, but worked because the base rate of 0.4 was too big, it slowed learning too much, and I knew from the previous competition that increasing the number of epochs could improve the result. Here, my logic was to simplify learning instead of increasing the number of epochs.<br>
Good luck to all of you and a peaceful sky above your head!</p> |
Google - American Sign Language Fingerspelling Recognition | Silver - LB 0.770 - Two Lines of Code! | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>That's my guess. Also if we remove missing hand frames, maybe certain consecutive hand activity blends together and fools the model into classifying the wrong letter. These are just guesses, i have not performed EDA nor ablation study to figure out why it helps. But using missing hand frames makes a big difference to the model for some reason.</p>
<p>Great trick <a href="https://www.kaggle.com/nightsh4de" target="_blank">@nightsh4de</a> Congratulations on 17th place solo Silver. You were so close to receiving another solo Gold, fantastic!</p>
<p>Thanks Ranamalla</p>
<p><a href="https://www.kaggle.com/yassinealouini" target="_blank">@yassinealouini</a> Congratulations on becoming Kaggle Discussion Grandmaster!</p>
<p>The first thing i did when analyzing the public notebook was to train longer than 50 epochs. That boosted LB from 0.697 to like LB 0.700 with 100 epochs. Then i increased the number of <code>FRAME_LEN</code>. That boost CV and LB too.</p>
<p>The next thing i did was analyze the preprocessing code. Lots of time we can improve computer vision, NLP, etc with better preprocess. I saw that the preprocess removed frames, so i tried training a model <strong>without</strong> removing any frames. And wow! The CV and LB boost a lot. Then i changed it to keep 50% frames and that boost CV and LB more and speed up training. In retrospect it makes sense with the CTC loss because the model needs to know how many spacers to add to the output. Providing the missing frames gives the model clues, i think. </p>
<p>Next I tried augmentation and training for more epochs. This continued to boost CV and LB. Next i tried simple changes to the architecture but I didn't have much success with that.</p>
<p>After reading other solutions, it seems like the way to boost more would be to apply even more aggressive augmentation and train longer.</p>
<p>Congratulations <a href="https://www.kaggle.com/goldenlock" target="_blank">@goldenlock</a> Amazing job achieving solo cash gold 3rd place!</p>
<p>I didn't think about keeping more non hand frames for the shorter videos (versus long videos), that might help. I did try both keeping 100% and keeping 50%. But i applied my logic to all videos and using 50% did better.</p>
<p>Going from 0% non hand to 50% or 100% was a huge boost. I couldn't believe the CV when i first saw it. But i submitted and the LB jumped up just as much.</p>
<p>Good question. I'm not sure how much exactly. But removing 50% was better than 0% for both CV and LB. And it made training faster.</p>
<p>Thank you Priyanshu1235</p>
<p>Thanks Kaggle and Google for hosting a fun ASL competition.</p>
<p>I joined a few days ago, so I didn't have time to build my own model. Instead, I began with the best public notebook <a href="https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-place?scriptVersionId=139048726" target="_blank">here</a> (version 17) and attempted to improve it. After making a few changes, I boosted the LB from 0.700 to an amazing 0.770! and obtained Silver medal !!</p>
<h1>Change Two Lines of Code</h1>
<p>The best public notebook is Rohith Ingilela's awesome public notebook <a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">here</a> which was improved by Saidineshpola <a href="https://www.kaggle.com/code/saidineshpola/aslfr-ctc-based-on-prev-comp-1st-place?scriptVersionId=139048726" target="_blank">here</a>. Version 17 of Saidineshpola's notebook achieves CV = 0.689 (scroll to bottom of version 17) and LB = 0.697.</p>
<p>That notebook uses TF Records made by Rohith Ingilela <a href="https://www.kaggle.com/code/irohith/aslfr-preprocess-dataset-tfrecords-mean-std" target="_blank">here</a>. An easy trick to boost the performance of the public notebook is create TF Records which keep frames where hands are missing. The TF Records made by linked notebook removes all frames without hands. Instead we can use <code>"output two"</code> below and keep 50% of the frames with missing hands below to boost CV and LB. Updated notebook published <a href="https://www.kaggle.com/code/cdeotte/2-lines-of-code-change-lb-0-760" target="_blank">here</a>.</p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/Aug-2023/asl_preprocess.png" alt=""></p>
<p>Here is preprocess code to use when making TF Records and during inference:</p>
<pre><code>hand = tf.concat(, axis=)
hand = tf.where(tf.math.is, , hand)
mask = tf.math.not, )
alternating_tensor = tf.math.equal( tf.cumsum(
tf.ones ))%, )
mask = tf.math.logical
</code></pre>
<h1>CTC (Connectionist Temporal Classification) Loss:</h1>
<p>In this competition, I learned about CTC loss. This loss is amazing! It allows us to create a model with variable length input and predict variable length output in one step. So we can do things like seq2seq without waiting for a sequential decoder to decode each step. Instead we predict the entire output at once super fast! Giving the model some of the frames with hands missing helps identify duplicates and transistions:</p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/Aug-2023/asl_ctc.png" alt=""></p>
<h1>Time Augmentation LB +0.004!</h1>
<p>The public notebook trains for 50 epochs, I found that training for more epochs continues to boost CV and LB score! My final submission trains for 200 epochs. Furthermore, we can add augmentation (i.e. regularization) which helps the model train longer, prevent overfitting, and generalize better.</p>
<p>Below we see the histogram of train data Number of Frames divided by Character Length of Target Phrase. From this plot, we see that the ratio varies a lot. Some videos have a different recorded frame rate than others and some participants sign faster than others.</p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/Aug-2023/frame_hist.png" alt=""></p>
<p>What this means is that the model has a hard time transfer learning one frame rate to learn about another frame rate. We can help the model by using time augmentation. For each input sequence, we can randomly shrink frame length by 50% or enlarge 150%. This will add lots of new train data and help the model learn about different frame rates. Here is augmentation code:</p>
<pre><code> tf.random.uniform(shape=(), minval=, maxval=)<.:
= tf.math.round( tf.random.uniform(
=(), minval = tf.cast(tf.shape(lip)[],tf.float32) / .,
= tf.cast(tf.shape(lip)[],tf.float32) * .) )
x in</code></pre>
<h1>Post Processing LB +0.004!</h1>
<p>Sometimes the model doesn't make a good prediction. The shortest train data is length 3. When the model predicts length 2 or less, we know it is a bad prediction. Therefore we can replace bad predictions with the best constant length prediction. Anokas found the best constant length prediction <a href="https://www.kaggle.com/code/anokas/static-greedy-baseline-0-157-lb" target="_blank">here</a>. We add this to our TF Lite mode with the following code:</p>
<pre><code>x = tf(tf(x) < , lambda: tf(
, tf.int64), lambda: tf(x))
</code></pre>
<h1>Solution Code</h1>
<p>I published a Kaggle notebook <a href="https://www.kaggle.com/code/cdeotte/2-lines-of-code-change-lb-0-760" target="_blank">here</a> demonstrating the above 3 changes. The first four bullet points below achieve <code>LB = 0.763</code>, then time augmentation boost <code>+0.004</code> and PP boost <code>+0.004</code>. Note that the second bullet point (about batch size) just makes things faster but doesn't change the CV nor LB score. The other bullet points are the key:</p>
<ul>
<li>Change 2 lines of code to keep 50% missing hand frames</li>
<li>Change batch size from 32 to 128 and learning rate from 1e-3 to 4e-3</li>
<li>Change FRAME_LEN from 128 to 216</li>
<li>Increase epochs 50 to 200</li>
<li>Add time augmenation</li>
<li>Add post process for preds less than 3 chars</li>
</ul>
<p>The original notebook resizes the frames to 128. So the original notebook "sees" all the frames. But the original notebook drops the frames without hands (before resize). If we just keep 50% frames without hands and resize to 128, we get a big boost in CV and LB. So in other words even with 128 in both the original and updated, just adding frames without hands (before resize) gives a big boost.</p>
<p>Hi <a href="https://www.kaggle.com/ankurlimbashia" target="_blank">@ankurlimbashia</a> As an Nvidia employee, I have access to Nvidia cloud GPUs. So in the past few days, I had a bunch of V100 GPUs running experiments in the cloud. </p>
<p>Thanks Gazuwu</p>
<p>Thanks Abishek</p>
<p>Thank you </p> |
Google - American Sign Language Fingerspelling Recognition | Some Notes | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Many more skilled participants have shared very rich and impressive solutions. I'm only documenting a few experimental insights to avoid adding something redundant to the discussion.</p>
<h1>LB History</h1>
<table>
<thead>
<tr>
<th></th>
<th>public LB</th>
<th>private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>max_len=188</td>
<td>0.770</td>
<td>0.741</td>
</tr>
<tr>
<td>max_len=320</td>
<td>0.776</td>
<td>0.744</td>
</tr>
<tr>
<td>Post Process by Chris Deotte</td>
<td>0.778</td>
<td>0.747</td>
</tr>
<tr>
<td>expand ratio 2->4</td>
<td>0.779</td>
<td>0.752</td>
</tr>
<tr>
<td>epochs 126->200</td>
<td>0.780</td>
<td>0.752</td>
</tr>
</tbody>
</table>
<h1>What Didn't Work</h1>
<ol>
<li><p>I attempted various normalization techniques, including global normalization, local normalization, and normalization centered around the nose. However, I'm unsure if there were any experimental errors, as I found that these approaches merely expedited the training convergence without improving the leaderboard performance. I'm uncertain if my conclusion is accurate.</p></li>
<li><p>Lowering the dropout of the final layer from 0.4 to 0.1 and removing dropout from all other layers would result in a decrease of 0.001 points in both the public test set and the private test set.</p></li>
<li><p>To place the batch normalization (BN) before the depthwise convolution (DW Conv) instead of after would result in a decrease of 0.001 points for both the public LB (Leaderboard) and private LB (Leaderboard).</p></li>
<li><p>Spatial Mask. It may lead to training instability when used. If other aspects are handled well (such as normalization), it might be usable.</p></li>
</ol> |
Google - American Sign Language Fingerspelling Recognition | [109th Place Solution] 1DConv+Transformer+Augmentation using train+supplemental data split by types | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Context</h1>
<ul>
<li>Business context: <a href="https://www.kaggle.com/competitions/asl-fingerspelling/overview" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/overview</a></li>
<li>Data context: <a href="https://www.kaggle.com/competitions/asl-fingerspelling/data" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/data</a></li>
</ul>
<h1>Overview of the approach</h1>
<p>I mainly followed the solutions from <a href="https://www.kaggle.com/code/irohith/aslfr-transformer" target="_blank">ROHITH INGILELA</a>, <a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference" target="_blank">Mark Wijkhuizen</a> and <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">hoyso48</a>. First, I modified Mark's solution to make it work in Colab notebook with TPU, which saved me a lot of training time. To use TPU, I secondly converted the dataset to tfrecords files. I managed to get these two steps done by learning from hoyso48's notebooks with a lot of trials and errors. When I converted data, I processed the data following Rohith's dominant hand algorithm. At this point, I got LB: 0.659. Third, I added hoyso48's 1DConv architecture to the transformer model, which gave the LB a 0.015 boost. Fourth, I added most of hoyso48's augmentation methods with some parameter-tuning, which gave the LB a solid 0.033 boost. <br>
I also tried out some of my ideas. 1) Added supplemental data with some pre-processing. Together with train/valid dataset splitting based on sequence types and participant ids, it showed slight LB improvement. 2) Labelled the dataset with types, i.e. phone, url, address, name, sentence. Performed multitasking training, i.e. predicting the types of the sequences and predicting the phrases as the same time, which actually dropped the LB. 3) Added a penalty in the loss function of Mark's to penalize the length difference between the true phrase and predicted phrase, which didn't improve the LB. More attempts will be discussed later. </p>
<h1>Details of the submission</h1>
<h2>Data processing:</h2>
<ol>
<li>Loaded original train_landmarks and supplemental_landmarks dataset to my google drive.</li>
<li>Split each original parquet file (contains about 1000 sequences) to multiple parquet files by sequence_id. Removed all the frames with no hand landmarks. It turned out the LB will be increased by a lot if leaving half of the missing-hand frames in the data according to <a href="https://www.kaggle.com/competitions/asl-fingerspelling/discussion/434353" target="_blank">CHRIS DEOTTE's solution</a>. Calculated the frame-to-phrase ratios using the number of frames that have hand landmarks, and saved them into the train_ratio.csv and supple_ratio.csv files.</li>
<li>Created a <a href="https://www.kaggle.com/datasets/joqueen/aslfr-all-landmarks-nonanhand" target="_blank">new Kaggle dataset</a> with the new parquet files (one parquet means one sequence) and new csv files.</li>
<li>Created tfrecords files from the new dataset in step 3 using the <a href="https://www.kaggle.com/joqueen/yu-aslfr-train-supple-cleaned-landmarks-tfr" target="_blank">Kaggle notebook</a>. <br>
4.1. Removed the samples in supplemental dataset that have phrase length longer than 31, as the max phrase length of train dataset is 31. <br>
4.2 Removed the duplicates in supplemental dataset that has the same participant_id and phrase, as there are a lot duplicates in phrase and in participant_id in supplemental dataset.<br>
4.3 Removed the samples with frame-to-phrase ratios smaller than 0.5, 1, or 2. It turned out when ratio equals to 1, it gave me the best LB.<br>
4.4 Split the data to 5 folds based on the phrase type and participant_id. Saved the data as tfrecord files as a <a href="https://www.kaggle.com/datasets/joqueen/aslfr-all-5fold-grpsplit-cln-1p0-31phrlen-dedup" target="_blank">new Kaggle dataset</a>.</li>
</ol>
<h2>Training:</h2>
<ol>
<li>As described in the overview, the main body of my solution is from <a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference" target="_blank">Mark Wijkhuizen</a> and <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">hoyso48</a>, i.e. 1DConv+Transformer+Augmentation. As I trained my model using TPU in Colab, here is my <a href="https://colab.research.google.com/drive/1IOkmBN558p8hB_bfF-g4KO7SrvQiFshC?usp=sharing" target="_blank">Colab notebook</a> for training. I'm not going to repeat the details again here, but I think there were a few learnings/observations worth mentioning:</li>
<li>Mark padded the phrase length to 128 on the decoder side, the same as the frame length on the encoder side. We don't have to match the dimension. The max phrase length is only 31 and already padded to 32. Instead of padding phrase further to 128, I modified the MHA block to be able to take two different dimensions, i.e. q_len and kv_len. To be honest, it didn't improve or decrease my LB, so Mark's MHA is perfectly fine, but it did save me some training time. </li>
</ol>
<pre><code> (tf.keras.layers.Layer):
():
(MultiHeadAttention,self).__init__()
self.d_model = d_model
self.n_heads = n_heads
self.kv_len = kv_len
self.q_len = q_len
self.depth = d_model //
self.scale = / tf.math.sqrt(tf.cast(self.depth, tf.float32))
self.wq = self.fused_mha(self.depth, q_len)
self.wk = self.fused_mha(self.depth, kv_len)
self.wv = self.fused_mha(self.depth, kv_len)
self.wo = tf.keras.layers.Dense(d_model, use_bias=)
self.softmax = tf.keras.layers.Softmax()
self.reshape = tf.keras.Sequential([
tf.keras.layers.Permute([, , ]),
tf.keras.layers.Reshape([self.q_len, self.depth]),
])
self.do = tf.keras.layers.Dropout(dropout)
self.supports_masking =
():
tf.keras.Sequential([
tf.keras.layers.Dense(dim, use_bias=),
tf.keras.layers.Reshape([, self.n_heads, dim // self.n_heads]),
tf.keras.layers.Permute([, , ]),
])
():
Q = self.wq(q)
K = self.wk(k)
V = self.wv(v)
x = tf.matmul(Q, K, transpose_b=) * self.scale
x = self.softmax(x, mask=attention_mask) @ V
x = self.reshape(x)
x = self.wo(x)
x = self.do(x, training=training)
x
</code></pre>
<ol>
<li>I increased the mha_dropout_ratio, mlp_dropout_ratio of decoder by 1.5 times and clf_dropout_ratio of the classifier by 2 times, to heavily regularize the decoder and prevent overfitting. It improved my LB by 0.006. This idea is inspired by a discussion commented by hoyso48 .</li>
</ol>
<pre><code>
x = Decoder(n_dec_blocks,
dec_dim,
n_mha_heads,
mha_dropout_ratio*,
mlp_ratio,
mlp_dropout_ratio*,
frame_len,
phrase_len,
)(x, phrase_inp, frames_inp)
x = tf.keras.Sequential([
tf.keras.layers.Dropout(clf_dropout_ratio*),
tf.keras.layers.Dense(N_UNIQUE_CHARACTERS,
activation=tf.keras.activations.linear,
kernel_initializer=INIT_HE_UNIFORM,
use_bias=),
], name=)(x)
</code></pre>
<h2>Inference</h2>
<p>My inference followed Mark's inference method. Here is the <a href="https://www.kaggle.com/joqueen/m12-yu-aslfr-inference" target="_blank">inference Kaggle notebook</a>, which reported both my highest public score 0.713 and my highest private score 0.665.</p>
<h1>What tried but didn't work (well)</h1>
<h2>Loss penalization</h2>
<p>In Mark's customized loss function, y_true and y_pred got truncated by the y_true length. y_true length is known, so how to truncate the y_pred is not from training process. I was thinking what if the y_pred is very long, but got truncated in the loss function, which may not really represent the loss.</p>
<pre><code> ():
idxs = tf.where(y_true != PAD_IDX)
y_true = tf.gather_nd(y_true, idxs)
y_pred = tf.gather_nd(y_pred, idxs)
y_true = tf.cast(y_true, tf.int32)
y_true = tf.one_hot(y_true, N_UNIQUE_CHARACTERS, axis=)
loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred, label_smoothing=, from_logits=)
loss = tf.math.reduce_mean(loss)
loss
</code></pre>
<p>So I added a penalty about the length difference between the y_true and y_pred, to force the model to generate y_pred with a similar length as y_true while keep the categorical_crossentropy optimal.</p>
<pre><code> ():
y_true_len = tf.cast(tf.argmax(tf.cast(tf.math.equal(y_true, PAD_IDX), tf.int32),axis=), tf.int32)
_idx = tf.argmax(y_pred, axis=)
_ = tf.math.equal(_idx, EOS_IDX)
_len1 = tf.cast(tf.argmax(tf.cast(_, tf.int32), axis=), tf.int32)
_no_eos = tf.math.logical_not(tf.reduce_any(_, axis=))
_len2 = tf.cast(_no_eos, tf.int32) * CFG.phrase_len
y_pred_len = _len1 + _len2
penal = tf.cast(tf.(y_true_len-y_pred_len), tf.float32)
penal = tf.math.reduce_mean(penal)
idxs = tf.where(y_true != PAD_IDX)
y_true = tf.gather_nd(y_true, idxs)
y_pred = tf.gather_nd(y_pred, idxs)
y_true = tf.cast(y_true, tf.int32)
y_true = tf.one_hot(y_true, N_UNIQUE_CHARACTERS, axis=)
loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred, label_smoothing=, from_logits=)
loss = tf.math.reduce_mean(loss)
loss + CFG.loss_coeff * penal
</code></pre>
<p>I was quite excited about this idea, and managed to code and run it through. But it still reduced my LB by 0.001 even after some fine-tuning. (sad face)</p>
<h2>multi-tasking training</h2>
<p>Inspired by Mark's solution, I categorized the train+supplemental data to five types, phone_number, url, address, name_like, sentence. It is obvious that each type is so different from the other types, in terms of the content, the length, the structure. I was thinking, maybe I can do multi-tasking - let the model do classification and phrase-prediction at the same time, which may force the model to figure out the different patterns for different types of samples. But this actually reduced my LB by about 0.1, which is a lot to me. </p>
<pre><code> model.(
optimizer=opt,
loss = [tf.keras.losses.CategoricalCrossentropy(from_logits=,label_smoothing=), loss_w_ls],
metrics = [[tf.keras.metrics.CategoricalAccuracy()], [TopKAccuracy()]],
steps_per_execution=steps_per_epoch,
)
</code></pre>
<h2>positional encoding</h2>
<p>Mark's method used trainable positional encoding. I switched it to the sin/cos positional encoding for encoder only, and actually it reduced my LB by 0.005. But I didn't try to switch it for decoder. </p>
<h2>a validation strategy</h2>
<p>I was struggling a lot on designing a good validation strategy that has the CV correlated to the LB well. Out of desperation, I even kept the all the validation data in their original form - before removing the missing-hand frames and removing the samples with low frame-to-phrase ratios. And calculated the Levenshtein distance on the raw valid data. However, it was very time consuming, my model training only took 45 min - 1.5 hour, depending on the parameters. But the Levenshtein distance calculation for validation took about 3 hours. And even with all the effort, I still didn't see strong correlation. </p>
<h2>CTC</h2>
<p>I tried out CTC a bit following the notebooks from <a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">ROHITH INGILELA</a> and <a href="https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu" target="_blank">GREYSNOW</a>. But due to time limitation, I didn't really figure it out in time. And it looks like the majority of the top-tier solutions used CTC.</p>
<h1>Sources</h1>
<p><a href="https://www.kaggle.com/code/irohith/aslfr-transformer" target="_blank">https://www.kaggle.com/code/irohith/aslfr-transformer</a><br>
<a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference" target="_blank">https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference</a>) <br>
<a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">https://www.kaggle.com/competitions/asl-signs/discussion/406684</a><br>
<a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place</a><br>
<a href="https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu" target="_blank">https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu</a><br>
<a href="https://www.coursera.org/learn/nlp-sequence-models?specialization=deep-learning" target="_blank">https://www.coursera.org/learn/nlp-sequence-models?specialization=deep-learning</a> (transformer network)</p>
<p>This is my first competition and first solution write-up. Please let me know if I missed anything or if any part of my explanation was unclear. Suggestions and discussions are welcome. Thank you.</p> |
Google - American Sign Language Fingerspelling Recognition | [12th solution] Full, reproducible solution with code | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I already wrote the gist of my solution <a href="https://www.kaggle.com/competitions/asl-fingerspelling/discussion/434363" target="_blank">here</a>. Here, I will give a more comprehensive summary that follows official writeup guidelines. I also finished cleaning and arranging my work <a href="https://github.com/shlomoron/Google---American-Sign-Language-Fingerspelling-Recognition-12th-place-solution" target="_blank">in my github</a>. I made efforts to make my solution as easy to follow and reproduce as possible. I saved everything as Colab or Kaggle notebooks that you should be able to run as is. I kept all the data in public Kaggle datasets. Please let me know if I missed anything; I will do my best to fix it. If anything needs to be clarified, ask me. </p>
<h3>Context section</h3>
<p>This is a summary of my 12th place solution to <a href="https://www.kaggle.com/competitions/asl-fingerspelling/overview" target="_blank">Google - American Sign Language Fingerspelling Recognition competition</a>.<br>
The data page is <a href="https://wwww.kaggle.com/competitions/asl-fingerspelling/data" target="_blank">here</a>.</p>
<h3>Overview of the Approach</h3>
<p>My model is a CTC encoder with transformers and convolution layers, the same as the one used in the previous competition <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406978" target="_blank">1st solution</a> with the CTC modification that was introduced <a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">by Rohith</a>. My only modification to the model (besides changing the size) is adding positional encoding right before the first transformer layer.<br>
For the features, I used a similar approach as the solution of the previous competition and took the same lips, nose, and hands landmarks. I did not use the eyes and used slightly different pose landmarks (added some). I used X and Y (without Z) and also used difference features with a skip of 1 and 2, also the same as the previous competition solution.<br>
For augmentation, I used the same augmentations as the previous competition solution, with a modification to all augmentations based on modifying/deleting data in a window. The original solution used a random window, but a random window give a lower probability of modifications in the edges. I changed it to a random circular/rolling window, i.e., instead of ignoring the window section that goes out of the frames length, I rolled it to the beginning of the sequencs and modified it too.<br>
For filtering the bad data, I used two-step filtering. In the first step, I filtered the data according to (number of frames with non-nan hands landmarks) > 2*(length of phrase) and trained a basic model. In the second step, I used the basic model to calculate the normalized Levenshtein distance scores of all the samples and filtered them according to the score with a threshold of >0.2. This filtering allowed me to add to my training a lot of samples that I filtered out in the first step.<br>
A 9,497,577 parameters model with the previous competition solution's augmentations trained on ~300 epochs got a public LB of 0.779. making it larger (15,471,112 parameters) and training for 500 epochs got a public LB score of 7.9. Adding the modifications to augmentations and second-step filtering and training for 1500 epochs got public LB 0.794 and private LB 0.779 (the final, 12th-place solution).<br>
For validation, I used the first 3,000 samples. Toward the end of the competition, I feared that I might be overfitting to existing signers, so I did one experiment with 1000 epochs and separated the validation fold by signers ID (I used five unique signers for validation with training on all the rest). Even after 1000 epochs, the scores on the validation fold did not suffer due to overfitting. Thus, I continued with the original validation since I preferred to train on samples from all the signers.<br>
I did most of my training on Colab TPU. They are cheap and easy to use with kaggle datasets (no storing or egress costs).</p>
<h3>Details of the submission</h3>
<p>Besides what I wrote in the previous section, I had to change the maximum frame number after finishing the training to 320 since my original 340-frame model could not complete the inference in time. Of course, I did previous experiments and expected the 340 max frames number model to complete the inference in time. I suspect that with more epochs, the complexity of the parameters is higher, leading to more complex quantization and, hence, more inference time. Of course, I had to quantize to 16-bit for my model to fit the 40MB limit. Also, I could not train it in 16-bit since I used TPU with their bfloats. However, the quantization did not have a significant effect on my scores. If it had any impact, it was less than 0.001.<br>
What did not work: mix-up augmentation and AWP, but with more time, I probably could have made them work, too. I just made some blunders at the beginning, and when I understood how to do things right, there was already not enough time to train new models.</p>
<h3>Sources</h3>
<p>As I wrote above, a lot of my work was based on:</p>
<ol>
<li><a href="https://www.kaggle.com/competitions/asl-signs/discussion/406978" target="_blank">previous competition 1st solution</a></li>
<li><a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">Rohith's notebook</a> (in particular, the CTC modification and TFlite submission code) </li>
</ol>
<p>My cleaned and reproducible solution can be found <a href="https://github.com/shlomoron/Google---American-Sign-Language-Fingerspelling-Recognition-12th-place-solution" target="_blank">on my GitHub</a>.</p>
<p>It was a great competition, and I enjoyed it a lot. Thank you, Google, and everyone who published code or participated in forum and code section discussions. You made this competition as approachable and enjoyable as it was.</p>
<p>First, a clarification- the frames with (number of frames with non-nan hands landmarks) > 2*(length of phrase) are the frames that I kept, the other ones were the removed frames.<br>
How did I come up with this idea- It was discussed in the forum at the beginning of the competition that there are a lot of bad samples with a very low number of frames, so everyone who read the discussions in the forum knew that this is a problem that should be solved. How exactly- it did not matter. There were all kinds of possible schemes: remove all samples with frame_num<N with some small N (say 10), remove all samples with frame_num<4phrase_len (I think <a href="https://www.kaggle.com/irohith" target="_blank">@irohith</a> used this method), etc. My method was simply another one that worked 'good enough' and looked quite sensible, so I stayed with it.<br>
The second step of filtering- well, there was no specific 'how I came up with this idea'; I simply came up one day with this idea that I can use my model to find previously discarded samples that are actually good. I did some experiments, and it worked like a charm…</p> |
Google - American Sign Language Fingerspelling Recognition | [1st place solution] Improved Squeezeformer + TransformerDecoder + Clever augmentations | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you for your questions.</p>
<blockquote>
<p>Have you personally studied sign language or interacted with deaf individuals while working on this project?</p>
</blockquote>
<p>I did not know any sign language before both competitions, but during competitions I also look at the specific domain and try to understand why a model behaves as it does, with respect to mistakes. I went through the different characters on a high level, just to get an understand what is needed to spell a character (single hand? two hands? more?) and how letters, digits and special characters are different. I think understanding of the subtleties helps in model design, because ideally the model is capable at addressing those. Here, understanding fingerspelling and how mediapipe works helped coming up with meaningful augmentations that help the model generalize to new signers. For letters I even spent an hour or two training signing skills via this online game (its quite fun)<br>
<a href="https://www.signlanguageforum.com/asl/fingerspelling/fingerspelling-game/" target="_blank">https://www.signlanguageforum.com/asl/fingerspelling/fingerspelling-game/</a></p>
<blockquote>
<p>If you were well-versed in sign language, would you approach the solution differently? If yes, how?</p>
</blockquote>
<p>I dont think so. I often approach problems iteratively. Train a model, look at the predictions and understand if I can find mistakes that are domain related and can be prevented by a better model design (or by improving data quality). It would be easier to understand the mistakes if I would be well-versed in sign language but the approach would be the same</p>
<ol>
<li>train the model, and upload the model weights to a kaggle dataset</li>
<li>create an inference kernel and link the kaggle dataset which contains the model weights</li>
</ol>
<p>I was not talking about raw validation score but rather about the usefulness of our model in the real world, as (at least thats how I understand) it will be directly deployed in an app to help parents learn fingerspelling and support them communicate with their kids. In the real world example users, know when the did not do a proper recording, so only the quality of the model with respect to correctly recorded sequences matters. And thats where our model is quite strong. I would be very interested in human level performance for the train/ test dataset, but I would assume our model is on the same level. Dont know if hosts evaluated this.</p>
<p>Let me comment on a few of your point. Wont go into details, just give some of my thoughts</p>
<blockquote>
<p>Well, I entered this competition as something to do and to run a couple of experiments. I've gone through a decent amount of the general learning stuff on kaggle. I don't have a background in coding (have a PhD in something else, so you know, I can probably learn things),</p>
</blockquote>
<p>nobody starts with ML and directly wins competitions. Having also no python nor ML knowledge I worked my ass off and got a place of 500/2000 in my first kaggle competition, which by the way was on speech recognition 6 years ago. But with perseverance and curiosity I continued learning competition by competition and build a skill or two since then. </p>
<p>Regarding your point of flipping hands and using face landmarks. Some signers tend to support their signing with lip movement, which can be supportive signal. Also, not all signs are single handed. E.g. <code>+</code> which is in nearly all phone numbers uses both hands</p>
<blockquote>
<p>the 0.84 score means, I think, that on an average 11-12-character phrase, there's nearly 2 changes necessary to get to the right phrase. From looking at the output, I think it's actually the case that you get a decent amount of perfect translation, but there are also a number that are far off. </p>
</blockquote>
<p>You need to keep in mind that 10% of the data is corrupted and without signal coming from artefacts where people just tapped the record button, and its impossible to predict the target. But those cases are not relevant to the final usability. For the sequences that contain the actual phrases, our model has a very high accuracy. </p>
<p>Thanks to kaggle and everyone involved for hosting such an interesting competition. It was a great extension to the isolated sign language classification and it was very interesting to see how much of speech-to-text research could also be applied to sign language fingerspelling. As always it was a great teaming experience with <a href="https://www.kaggle.com/darraghdog" target="_blank">@darraghdog</a> </p>
<h2>TLDR</h2>
<p>Our solution is based on a single encoder-decoder architecture. The encoder is a significantly improved version of Squeezeformer, where the feature extraction was adapted to handle mediapipe landmarks instead of speech signals. The decoder is a simple 2-layer transformer. We additionally predicted a confidence score to identify corrupted examples which can be useful for post-processing. We also introduced efficient and creative augmentations to regularize the model, where the most important ones were CutMix, FingerDropout and TimeStretch, DecoderInput Masking. We used pytorch for developing and training our models and then manually translated model architecture and ported weights to tensorflow from which we exported to tf-lite.</p>
<h2>Cross validation</h2>
<p>We split the training data into 4 folds by signer. In the beginning we had nearly perfect correlation between CV and public LB with this approach. With higher scores improvements on CV reflected a bit less on LB, mostly due to the fact that the LB score was always decently higher and hence saturated earlier. Most of the time we only trained and tracked the score of fold0 and not all folds. </p>
<h2>Data preprocessing</h2>
<p>In total 130 key points were used. These consisted of 21 key points from each hand, 6 pose key points from each arm, and the remaining 76 from the face (lips, nose, eyes). Locally the 130 key points were cached to .npy files for fast data loading. <br>
Prior to data augmentations, the data was normalized with std/mean and nans were zero filled. </p>
<h2>Augmentations</h2>
<p>Augmentations were essential to prevent overfitting, generalize to new signers and enable deep models. We used augmentations which were popular in the first ASL competition but also came up with a lot of new creative augmentations and some have proven to be very effective. </p>
<ul>
<li>Resizing along time axis.</li>
<li>Shift the sequence along the time axis. </li>
<li>Windowed resizing along time axis (similar to warping).</li>
<li>Left-right flip of keypoints. </li>
<li>Cutmix of samples timewise - draw a random percentage between [0,1] and cut 2 sequences and related phrases at that percentage and mix. Mixing only within same signer was best</li>
<li>Spatial affine - scale, shear, shift and rotate. </li>
<li>Drop/Zero-fill between 2 to 6 different fingers over 2 to 3 time windows. </li>
<li>Drop/Zero-fill either all face landmarks or all pose landmarks. </li>
<li>In rare cases (~5% of samples) drop/zero-fill all hand landmarks. </li>
<li>Temporal masking (zero-fill) in windows of different sizes or counts. </li>
<li>Spatial masking </li>
</ul>
<p>Most augmentations were applied to 50% of the samples, except for resizing and spatial affine which were applied to ~80% of samples. </p>
<p>After augmentation, samples with more than 384 frames were resized along time axis, with channel-wise linear interpolation. Samples of less than 384 were padded to 384 for training only. tf-lite ran on variable length samples. <br>
No frames were dropped in preprocessing. </p>
<h2>Model</h2>
<p>In general, we observed that a deeper model gives significant gains (if we are able to prevent overfitting). As a consequence not only regularization techniques like augmentations are essential, but also every improvement in computational efficiency creates space to use deeper models and hence is equally important as the model architecture itself.</p>
<p>Our model consists of 3 parts, Feature Extraction, Encoder, Decoder which are shown in the image below</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1424766%2Fdc7c0fc365f54fb4d35f03da1748ed3b%2FScreenshot%202023-08-25%20at%2012.47.53.png?generation=1692960500706760&alt=media" alt=""></p>
<p>We interpret the data like a 3 channel image, where width is defined by the number of frames, height is given by the number of the selected 130 landmarks and channels are given by raw xyz coordinates. <br>
The feature extraction is based on a 2D convolution followed by batchnorm and a linear layer on the flattened features to extract features per frame. We have 5 of this feature extraction modules, one for all landmarks at once and one per landmark type (left_hand, right_hand, face, pose). The all-landmark module outputs 208 dim vector/ frame. The other 4 output 52 dim vectors each which are then concatenated to have also 208 dims. We had those two 208-dim vectors per frame and get a (batch_size x 384 x 208) input for our encoder where 384 is the maximum sequence length we chose.</p>
<p>The main component of our model is an encoder which was adapted from the Squeezeformer architecture. We did not use the actual “squeeze” idea, i.e. a temporal Unet, but used the general architecture of Squeezeformer Blocks which consist of a combination of MultiHeadSelfAttention (MHSA), Convolution and FeedForward modules. We made several improvements to this architecture:<br>
ASR conformers (and Squeezeformer) use relative positional encoding which allow the self-attention module to generalize better on different input lengths. Relative positional encoding is performance intensive, as well as using many parameters, as they are stored separately in each layer. Replacing this with Llama attention which uses rotary embeddings sped up training ~2X and tf-lite inference approx ~3X allowing larger models to be used. In addition, we cached the rotary embeddings once and fed them into each layer with the input data so they are not duplicated in each layer. This resulted in 20% less parameters in the model. We saw no benefit in using time reduction which was introduced with Squeezeformer. So in our model all layers had the same sequence length as the original input. As suggested in the Squeezeformer paper, the pre-Layer Norm from the Macaron structure is redundant and was replaced with a learnable scaling layer which scales and shifts the activations. </p>
<p>For decoding we used a simple 2 layer transformer decoder which is similar to hugging faces <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/speech_to_text/modeling_speech_to_text.py#L857" target="_blank">Speech2TextDecoder</a>, which outputs a sequence prediction. We then used cross entropy loss for training our model End2end. An extra cross entropy auxiliary loss of the reversed sequence was used. A causal decoder mainly uses encoder cross attentions for the sequence's beginning and previous characters and cross attentions for the end. To improve the model's accuracy, we use a separate causal decoder on the reversed sequence as an auxiliary loss, making the model rely more on the encoder cross attention for the label's end. For decoder inference early stopping and past key value caching was used which sped up inference significantly. It should be noted that we found a transformer based Decoder superior to a CTC based decoding, even in a setting where computational efficiency matters a lot. </p>
<p>Additionally to the decoder, we also added a single linear layer to take the features of the first token of the encoder output to predict a confidence score, which helps to identify garbage data and can be used in post-processing. As a target for this we used normalized levensthein distance clipped to [0,1] of OOF predictions of a decent previous model.</p>
<p>We explored and trained all our models in pytorch, but whenever we deemed it good enough for a submission we translated each component manually to tensorflow and ported weights from our pytorch models. </p>
<h2>Training procedure</h2>
<p>Models were trained with a cosine learning rate schedule for 400 epochs with peak LR of 0.0045, weight decay of 0.08, 10 epochs warmup, mixed precision and an effective batch size of 512 samples. Dropout of 0.1 was used in the transformer encoder/decoder layers. It was important to train with mixed precision in order to leverage fp16 inference without performance drop. Training with fp32 and using tf-lite fp16 inference causes a drop of ~0.01 in CV vs LB. </p>
<p>tf-lite inference used a single sample without padding, while model training was performed with time padded mini-batches. To avoid the model learning with pads, and ensure optimal inference runtime, the feature extractor and Macaron structure encoder layers were masked time wise during training. This needed to be manually implemented in pytorch on each layer. This took some effort, but paid off by significantly speeding up inference. As <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">1st place team</a> in the previous ISL competition explained, this is much easier to do in tensorflow as keras has an off the shelf masking layer. </p>
<p>Model training and tf-lite inference ran in fp16, so tf-lite files consumed almost half the disk size of of fp32. This was important, as the 40MB size was our limitation in the end. The two final model seeds measured 39988kb. </p>
<h2>Postprocessing</h2>
<p>The main idea of our postprocessing is to replace poor predictions with a dummy phrase which has a small levensthein distance to the train/ test data. <a href="https://www.kaggle.com/anokas" target="_blank">@anokas</a> showed in his <a href="https://www.kaggle.com/code/anokas/static-greedy-baseline-0-157-lb" target="_blank">notebook</a> why '2 a-e -aroe' is a good candidate for that. Most of the poor prediction resulted from corrupted input data often only a few frames long. We used a confidence score predicted by our model as basis. Whenever the confidence score is below 0.15 or the sequence is shorter than 15 frames we replace the prediction with '2 a-e -aroe'.</p>
<h2>Supplemental Data</h2>
<p>We only marginally profited from using the supplemental data. We think the main reason is that although there are 50k samples in this supplemental data there are only 500 unique phrases, and hence the model rather learns to classify then to actually decode character-by-character. We tried a lot of approaches but only the following one gave a small boost (0.838 -> 0.839): <br>
First we group the supplemental data by phrase, which only leaves us with 500 groups. In each epoch of training we add one sample per group to the training dataset for our model. That means in each epoch we use 50k samples of the training data and only 500 samples of the supplemental data. </p>
<h2>Ensembling</h2>
<p>Our final submission is a 2-seed ensemble of our model trained on the complete training data (fullfit). We average resulting logits in each decoding step for ensembling.</p>
<h2>What did not help</h2>
<ul>
<li>Fully using supplemental data</li>
<li>Using edit distance as loss (tried different approaches)</li>
<li>CTC loss (even as an auxiliary loss it hurt score)</li>
<li>Label smoothing</li>
<li>AWP - kept getting nans with FP16</li>
<li>TTA (flip/stretch)</li>
<li>Mixup of hidden layers & Specaugment++</li>
<li>Beam search decoding (too costly)</li>
</ul>
<h2>Ablation study (roughly)</h2>
<h4>Augmentations</h4>
<ul>
<li>Cutmix +0.005</li>
<li>FingerDropout +0.005</li>
<li>Face/PoseDropout +0.005</li>
<li>masking decoder inputs +0.003</li>
</ul>
<h4>Model improvements</h4>
<ul>
<li>CNN Feature extraction +0.005</li>
<li>2-branch Feature extraction with indiv norm +0.003</li>
<li>Squeezeformer over 1stplace Net of 1 round +0.005</li>
<li>Decoder over CTC +0.003</li>
<li>Confidence over simple rules for post-processing +0.002</li>
</ul>
<h4>Efficiency Improvements:</h4>
<ul>
<li>Deeper model due to fp16 +0.003</li>
<li>Deeper model due to llama attention +0.003</li>
<li>Deeper model due to masking/ variable sequence len +0.005</li>
<li>Deeper model due to caching/ early stopping in decoder +0.005</li>
</ul>
<h4>Postprocessing</h4>
<ul>
<li>Replace bad predictions with dummy phrase +0.006</li>
</ul>
<h2>Used tools/ repos</h2>
<ul>
<li>Pytorch/Tensorflow/Tf-lite (no onnx this time)</li>
<li>Huggingface</li>
<li>Albumentations (adapted their framework for using things like OneOf or Compose, but wrote our own augmentation implementations)</li>
<li>Neptune.ai was our MLOps stack to track compare and share models. Below are example training runs using different model parameters and hardware (a100 card vs kaggle kernel). The data loading in the kaggle kernel below was slow and could probably be sped up with some work. </li>
</ul>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1424766%2F4693e3379ea6a1631bb3cb7b9044d42a%2FScreenshot%202023-08-25%20at%2012.58.07.png?generation=1692961107306495&alt=media" alt=""></p>
<h2>Code & model weights</h2>
<p><a href="https://github.com/ChristofHenkel/kaggle-asl-fingerspelling-1st-place-solution" target="_blank">https://github.com/ChristofHenkel/kaggle-asl-fingerspelling-1st-place-solution</a></p>
<h2>Paper</h2>
<p>tbd. Due to the novelty of our approach we are thinking about summarizing it in a paper.</p>
<p><strong>Thank you for reading, questions welcome</strong></p>
<p>training and inference is completely separate. We train locally using pytorch, then convert trained model to tf-lite and only upload submission.zip to kaggle kernel to run inference. <br>
Inference runtime is 4.5h</p>
<blockquote>
<p>The peak LR (0.0045) and weight decay (0.08) look pretty fine grained.</p>
</blockquote>
<p>It looks like its fine grained but it was rather the opposite. We started with some learning rate reported in the original SqueezeFormer paper, had some miscommunication within the team with respect to using DDP (which means lr / batch size should be adjusted) and ended up with a LR of 0.0045 more or less by accident, I tested a slightly different higher/ lower LR later and it did not change much, so we sticked with it. <br>
For weight decay we started with 0, then tried 0.01 which gave a significant improvement, then 0.05 which helped even more. Finally we tried 0.08 which was slightly better than 0.05 but in range which I would say its just noise, so we thought we keep at that. </p>
<p>Solely by hand. What came in handy was that there is a more or less consistent implementation of squeezeformer in both here</p>
<p>torch: <a href="https://github.com/upskyy/Squeezeformer/tree/main" target="_blank">https://github.com/upskyy/Squeezeformer/tree/main</a><br>
tensorflow: <a href="https://github.com/kssteven418/Squeezeformer/tree/main" target="_blank">https://github.com/kssteven418/Squeezeformer/tree/main</a></p>
<p>Also, Speech2TextDecoder and LLamaAttention is implemented in huggingface in both, torch as well as tensorflow. So its some work to translate the architecture solely by hand, but less work than you would expect. More tricky translations were the custom masking, and the caching/ early stopping of the decoder</p>
<p>The exercise was also useful to refresh some tensorflow skills, as I had not used it for years. </p>
<blockquote>
<p>What dimensions did you use in the encoder in the end? The screenshot shows 128, 168 and 192.</p>
</blockquote>
<p>Encoder was 14x SequeezeFormerBlocks with 208 dim. 14 layers seemed optimal and then we maximized the dim to fit 2 seeds within the 40MB restriction.</p>
<blockquote>
<p>What kind of hardware did you use to train?</p>
</blockquote>
<p>I mainly used NVIDIA V100 16GB GPUs</p>
<p>gradient accumulation (just google it) is your friend when you want to use higher batch size. Related to NaNs while training its really hard to deal with them, hard to give some advice, since it depends on all kind of factors</p>
<p>OOF means out-of-fold predictions. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1424766%2F91c133b7b849bc0bd9c4ce0b05dcb492%2FScreenshot%202023-08-29%20at%2009.24.15.png?generation=1693293984960629&alt=media" alt=""></p>
<p>We had you train a model for each fold and concatenate the resulting sets of validation scores. This gives you a normalized levensthein score for each data sample. We used this as an auxiliary target for training a new model. </p>
<p>Basically calculate levensthein distance for each data sample and clip to [0,1]. Then use that as auxiliary loss using Binary Crossentropy loss. Combine with the "normal" loss using weighted average with weight of 0.98 for the normal loss and 0.02 for the auxiliary loss. You can find the details here</p>
<p><a href="https://github.com/ChristofHenkel/kaggle-asl-fingerspelling-1st-place-solution/blob/main/models/mdl_2_pt.py#L867-L871" target="_blank">https://github.com/ChristofHenkel/kaggle-asl-fingerspelling-1st-place-solution/blob/main/models/mdl_2_pt.py#L867-L871</a></p> |
Google - American Sign Language Fingerspelling Recognition | [28th Place Solution] Pre Training on Supplemental Data gives 0.01 LB Improvement | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Acknowledgements</h2>
<p>Firstly, I'd like to extend my deepest gratitude to my teammates:</p>
<ul>
<li><a href="https://www.kaggle.com/chellyfan" target="_blank">@chellyfan</a></li>
<li><a href="https://www.kaggle.com/chuansj" target="_blank">@chuansj</a></li>
</ul>
<p>Their enormous effort has been instrumental in this competition. </p>
<p>I'd like also thanks to the authors of following notebooks. Our success wouldn't have been possible without the insights and techniques we adopted from these notebooks. A big thanks to you.</p>
<ul>
<li><p><strong>@irohith</strong> for his excellent preprocessing and training notebooks:</p>
<ul>
<li><a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">ASLFR CTC based on prev comp 1st place</a></li>
<li><a href="https://www.kaggle.com/code/irohith/aslfr-preprocess-dataset-tfrecords-mean-std" target="_blank">ASLFR preprocess dataset TFRecords mean std</a></li></ul></li>
<li><p><strong>@hoyso48</strong> for his 1st place solution from a previous competition:</p>
<ul>
<li><a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training" target="_blank">1st Place Solution Training</a></li></ul></li>
<li><p><strong>@greysnow</strong> for the CTC on TPU notebook:</p>
<ul>
<li><a href="https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu" target="_blank">ASLFR CTC on TPU</a></li></ul></li>
<li><p><strong>@royalacecat</strong> for the notebook on more blocks with quantization:</p>
<ul>
<li><a href="https://www.kaggle.com/code/royalacecat/the-deeper-the-better" target="_blank">The deeper, the better</a></li></ul></li>
</ul>
<h2>TL;DR</h2>
<p>Our solution is based on the CTC open source notebook. Here are the key improvements we introduced (all scores are public LB):</p>
<ul>
<li>Only filter <strong>full NaN frames</strong> when generating tfrecord files on data preprocessing. (0.687->0.705)</li>
<li>Adding more numbers of block in the model as described in <a href="https://www.kaggle.com/code/royalacecat/the-deeper-the-better" target="_blank">The deeper, the better</a>. (0.705->0.716)</li>
<li><strong>Increased frame length</strong> from 128 to 256. (0.716->0.746)</li>
<li><strong>Enhanced feature selection</strong> by adding more face and pose indices, increase from 96 to 128 indices. (0.746->0.763)</li>
<li>Incorporated <strong>CTC loss with label smoothing</strong> for added regularization. (0.763 ->0.766)</li>
<li><strong>Pretrained our model</strong> on the supplemental dataset. Pre train 80 epochs on supply set then 80 epochs on main dataset. (0.766->0.777)</li>
<li>Adopted the <strong>motion feature</strong> technique from a previous competition. (0.777->0.781)</li>
<li>Increase training epochs on main dataset from 80 to 120 (0.781->0.782)</li>
</ul>
<h2>Data Preprocessing</h2>
<p>Referring to <a href="https://www.kaggle.com/irohith" target="_blank">@irohith</a>'s preprocessing notebook, we made changes by adding more face and pose indices. We selected the new indices based on their variance — higher variance indicates more information.</p>
<p>Initially, the indices were:</p>
<pre><code>LIP = [
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , ,
]
LPOSE = [, , , , ]
RPOSE = [, , , , ]
POSE = LPOSE + RPOSE
</code></pre>
<p>We then updated them to:</p>
<pre><code>LIP = [
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , ,
, , , , , , , , , ,
]
face_id = [,,,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,]
k face_id:
k LIP:
LIP.append(k)
l = (LIP)
LIP = LIP[:(l - l/)]
LPOSE = [, , , , , , , , , , , , , , , ]
RPOSE = [, , , , , , , , , , , , , , , ]
POSE = LPOSE + RPOSE
</code></pre>
<p>filter out full Nan frame</p>
<p>origin notebook:</p>
<pre><code>hand = tf.concat([rhand, lhand], axis=)
hand = tf.where(tf.math.is_nan(hand), , hand)
mask = tf.math.not_equal(tf.reduce_sum(hand, axis=[, ]), )
</code></pre>
<p>update to </p>
<pre><code>hand = tf.concat([rhand, lhand,lip,rpose,lpose], axis=)
hand = tf.where(tf.math.is_nan(hand), , hand)
mask = tf.math.not_equal(tf.reduce_sum(hand, axis=[, ]), )
</code></pre>
<p>Those new indices along with 256 frame length gives us about 0.02 LB improvement!</p>
<h2>Motion feature</h2>
<p>see <a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training" target="_blank">1st Place Solution Training</a></p>
<h2>CTC Loss with Label Smoothing</h2>
<p>To enhance our model's stability during training, we implemented a CTC loss with an added regularization component. By combining the CTC loss with a Kullback-Leibler (KL) divergence, we introduced label smoothing to the model. Smooth weight = 0.7 works best for our model</p>
<pre><code> ():
label_length = tf.reduce_sum(tf.cast(labels != pad_token_idx, tf.int32), axis=-)
logit_length = tf.ones(tf.shape(logits)[], dtype=tf.int32) * tf.shape(logits)[]
ctc_loss = tf.nn.ctc_loss(
labels=labels,
logits=logits,
label_length=label_length,
logit_length=logit_length,
blank_index=pad_token_idx,
logits_time_major=
)
ctc_loss = tf.reduce_mean(ctc_loss)
kl_inp = tf.nn.softmax(logits)
kl_tar = tf.fill(tf.shape(logits), / num_classes)
kldiv_loss = (tf.keras.losses.KLDivergence(tf.keras.losses.Reduction.NONE)(kl_tar, kl_inp)
+ tf.keras.losses.KLDivergence(tf.keras.losses.Reduction.NONE)(kl_inp, kl_tar))/
kldiv_loss = tf.reduce_mean(kldiv_loss)
loss = ( - weight) * ctc_loss + weight * kldiv_loss
loss
</code></pre>
<h2>Pre-training the Model on the Supplemental Dataset</h2>
<p>During our experimentation, we found a significant insight: training solely on the <strong>supplemental dataset</strong> yielded a LB score of 0.367. This highlighted the potential value embedded within the supplemental data.</p>
<p>We decided to first pre-train our model on the supplemental dataset, then loaded these pre-trained weights to further train the model on the main dataset. We tested multiple epochs: 40, 60, and 80 for pre-train. 80 epochs works best and give a improvement of 0.013 on the LB score.</p>
<h2>What We Tried, But Didn't Work</h2>
<ol>
<li><p><strong>Augmentation</strong>:</p>
<ul>
<li><strong>Random Affine Transformation</strong></li>
<li><strong>Random Part Removal</strong>: We tried dropping certain parts (like lip, lpose, rpose, lhand, rhand) by setting them to NaN with a 5% probability. </li>
<li><strong>Feature Switch for Phrases</strong>: switch features for phrases within the same category.</li></ul>
<p>In 2nd place solution, <a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a> mention that some augmentation didn't improve the model during short epoch training but in longer training would have the effect. This could applied to our case as well but we haven't verified yet.</p></li>
<li><p><strong>Switching to GIC-CTC</strong>:</p>
<ul>
<li><strong>Reference Paper</strong>: <a href="https://ieeexplore.ieee.org/document/10094820" target="_blank">Improving CTC-Based ASR Models With Gated Interlayer Collaboration</a></li>
<li>Increasing parameters led to our model exceeding the 5-hour inference time limit.</li></ul></li>
</ol>
<h2>What We could Imporve</h2>
<ol>
<li>long epochs training. We only train 120 epochs for final submission, which is much less compare to other top place solution (usually 300-500 epochs). We already saw a 0.001 LB improve from 80 epochs to 120 epochs on the final day, but it's too late</li>
<li>Adjust the leaning rate and weight decay more carefully. We simply use the cosine decay lr scheduler in the public notebook and set weight decay to 0.05</li>
<li>Utilized AWP for longer epoch training</li>
</ol>
<h2>Notebook:</h2>
<p><a href="https://www.kaggle.com/code/wuhongrui/aslfr-gcs-path" target="_blank">https://www.kaggle.com/code/wuhongrui/aslfr-gcs-path</a><br>
<a href="https://www.kaggle.com/wuhongrui/aslfr-training" target="_blank">https://www.kaggle.com/wuhongrui/aslfr-training</a><br>
<a href="https://www.kaggle.com/wuhongrui/ctc-final-inference-notebook" target="_blank">https://www.kaggle.com/wuhongrui/ctc-final-inference-notebook</a></p>
<p>Training notebook is written specific for training on Google Colab. Frist use gcs-path notebook check the path in training notebook. Set USE_SUPPLY = True first to train supply set, then set USE_VAL = True to load pre-train weight and train main data set.</p>
<p>To use it on Kaggle TPU, change the file address to corresponding Kaggle input address and you NEED to modify the CTC loss. Check <a href="https://www.kaggle.com/code/shlomoron/aslfr-ctc-on-tpu" target="_blank">ASLFR CTC on TPU</a></p>
<p>Thanks for your great insight! It's interesting to see the impact of pre-training and the number of epochs on your model's performance. We overlooked importance of the long epoch training in this competition, and as you mentioned, the weights initialization maybe is less significant for long epoch.</p>
<p>Congratulation again for your amazing solution of 1st place in this competition !</p> |
Google - American Sign Language Fingerspelling Recognition | [3rd place solution with code] 17 layers squeezeformer with timerduce and ROPE | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>The result is similar as other solutions which use post trick like special output for short predictions. 2-3 point online I think.</p>
<p>enable xla will be even slower</p>
<p>Thanks <a href="https://www.kaggle.com/darraghdog" target="_blank">@darraghdog</a> , I also learned a lot from your sharing of last competion. <br>
For awp, I used fp32, it will also cause nan for me at the begging if using fp16 I do not kown why.<br>
So I will use fp16 + no awp first then change to load model and train with fp32 + awp. <br>
Anyway awp work and give better result especially for less epochs, a boost of 2-3 points, but if you train like 300+ epochs the boost might be less and it is also very time costing as you need to start awp training early.</p>
<p>Squeezeformer is fast you could also make the encoder units less for me I used 200. Also I used smaller attention head dim 32. Actually I tested we could submit model with 20 layers which use 0.81s/it and finish just in less then 5 hours.</p>
<p>Here mean for each ctc output step you could adjust the prob of blank index, for example if blank index prob is 0.25 and it is still the largest prob for this step. If no post rule then will output blank index, but if using the post rule it will output a char in our vocab.</p>
<p>Thanks, I will share the code soon.</p>
<p>This is an intesting game, I learned a lot from </p>
<p><a href="https://www.kaggle.com/code/hoyso48/1st-place-solution-training" target="_blank">https://www.kaggle.com/code/hoyso48/1st-place-solution-training</a><br>
<a href="https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place" target="_blank">https://www.kaggle.com/code/irohith/aslfr-ctc-based-on-prev-comp-1st-place</a><br>
<a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference" target="_blank">https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference</a></p>
<h1><strong>Preprocss</strong></h1>
<ol>
<li><strong>Do not throw away frames witout hands!</strong></li>
<li>Use as much info as possible, (hands, lips, eye, nose, pose) , use (x,y,z)</li>
<li>Use more frames, resize to 320 frames for model training.</li>
<li>I used <strong>original + normalized + abs position(/1000.)</strong> as input feats(total 384 * 2 + 1 = 769). <br>
normalized feats help converge much faster but I found original feats also helps.</li>
</ol>
<h1><strong>Aug</strong></h1>
<p>I followed last competion 1st solution, and found the most important aug are </p>
<ol>
<li><strong>time scale (interp1d)</strong></li>
<li><strong>time dim mask</strong><br>
I used heavy mask here which will mask some time seq and aslo will <strong>randomly mask 50% frames</strong></li>
<li>affine <br>
follow preve 1st solution with prob 0.75, for left-right flip only with prob 0.25</li>
</ol>
<h1><strong>Training</strong></h1>
<ol>
<li>I used <strong>train data + sup data combined training with sup data weight set to 0.1</strong> for 400 epochs.</li>
<li>batch size 128, max lr 2e-3, lr scheduler using linear decay with 0.1 epochs warmup , adam optimizer</li>
<li>Awp training started from epochs * 0.15, with adv_lr 0.2 and adv_eps 0.</li>
<li><strong>Fintune with train data only for 10 epochs</strong> with max lr 1e-4, awp start from epoch 2. </li>
</ol>
<h1><strong>Postdeal</strong></h1>
<p>I used <strong>rule for blank index(0)</strong><br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F42245%2F54e452eca19b2ee1610a7ecef4ea7cdc%2F1.png?generation=1692937017778775&alt=media" alt=""></p>
<h1><strong>Model</strong></h1>
<ol>
<li><strong>Squeezeformer</strong> works best, it is a bit faster then conformer. (Code from NEMO)</li>
<li>In order to make net deeper I used <strong>1 down sampling layer to reduce frames from 320 to 160</strong>.<br>
This is mainly helpful for adding more encoder layers, and also can allow using complex encoder layers.</li>
<li><strong>Relative pos encoding</strong> affect the performance so much, I found <strong>ROPE(by Jianlin Su)</strong> perform best and super fast. (code from huggingface implementation)</li>
<li><strong>Dropout is super important, I used final cls_drop=0.1 only, no dropout for other layers.</strong></li>
<li>I learned from 1st-place-solution-training that <strong>stochastic path</strong> is <strong>super important to avoid overfit for deep network</strong>. So I used it in squeeeze former block for each layer like below(notice the InstDropout and 0.5 skip factor all super important for final performance)<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F42245%2Ffb17306d174a4bd7a4b81ad0acdc0ade%2F2.png?generation=1692937044317556&alt=media" alt=""><br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F42245%2F4834f8f3d02efab8d8f0bbe32a79f9a4%2F3.png?generation=1692937055628577&alt=media" alt=""><br>
Overall model arch below:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F42245%2F68866c3f59e3e6b2f308a54fc8b94248%2F4.png?generation=1692937099435075&alt=media" alt=""></li>
</ol>
<h1><strong>Others</strong></h1>
<ol>
<li>For me (using 4090), torch much faster then tf (3-4 times faster) </li>
<li>I used tf at first and swich to torch in the last month which help to speedup experiments a lot. <br>
Speed is only one factor, another important thing is I could easily try opensource code of ASR like NEMO or espnet.</li>
<li>I used <strong>nobuco</strong> to convert torch model to keras, it works like a charm. </li>
<li>I still used tf for prorcess/aug and post process and also use tfrecord as input format, I wrote a torch iterable dataset which wrap tfrecord reader.</li>
</ol>
<h1><strong>TODOS</strong></h1>
<p>Due to time limit, I could not finish more experiments at last days, but some possible improvements might be</p>
<ol>
<li>Model can be deeper up to <strong>20 layers</strong><br>
20 layer model perform better then 17 layers but I only trained 300 epochs which perform not as good as 17 layers + 400 epochs.</li>
<li>More epochs training, maybe 500 or 600 ? <br>
For 17 layer model from 300 to 400 improve LB 4 points and PB 2 points, so might sitll could train more epochs and might use 20 layer model for more epochs help even more:)</li>
<li>From what I learned from other solutions, it seems I missed some major points here</li>
</ol>
<ul>
<li>cutmix<br>
this is a pity, I planned to do this at the begging but did not try it, as I found hard mask of frames(50%+) worked very well, I should have realized that cut mix might help even more. <br>
simple concat 2 instances <br>
concat with some ratio like 0.7 and 0.3 <br>
concat with using ctc segmentation </li>
<li>seq2seq method and ctc+attention decode method <br>
I tried seq2seq using tf at the begging of this competition but not give good results, should have tried it after changing to use torch with squeezeformer encoder. </li>
<li>input len mask to speedup infer</li>
<li>try even more max input frames from 320 to 384 or 512(with input len mask infer)</li>
</ul>
<h1><strong>Code</strong></h1>
<p>Opensource all codes here: <br>
<a href="https://www.kaggle.com/code/goldenlock/3rd-place-step1-gen-tfrecords-for-train" target="_blank">https://www.kaggle.com/code/goldenlock/3rd-place-step1-gen-tfrecords-for-train</a><br>
<a href="https://www.kaggle.com/code/goldenlock/3rd-place-step2-gen-tfrecords-for-supplement" target="_blank">https://www.kaggle.com/code/goldenlock/3rd-place-step2-gen-tfrecords-for-supplement</a><br>
<a href="https://www.kaggle.com/code/goldenlock/3rd-place-step-3-gen-mean-and-std" target="_blank">https://www.kaggle.com/code/goldenlock/3rd-place-step-3-gen-mean-and-std</a><br>
<a href="https://www.kaggle.com/code/goldenlock/3rd-place-step-4-train-squeezeformer" target="_blank">https://www.kaggle.com/code/goldenlock/3rd-place-step-4-train-squeezeformer</a><br>
<a href="https://www.kaggle.com/code/goldenlock/3rd-place-step-5-torch2keras-using-nobuco" target="_blank">https://www.kaggle.com/code/goldenlock/3rd-place-step-5-torch2keras-using-nobuco</a><br>
<a href="https://www.kaggle.com/code/goldenlock/3rd-place-step-6-inference" target="_blank">https://www.kaggle.com/code/goldenlock/3rd-place-step-6-inference</a> <br>
Notice I did not reproduce my final results using kaggle notebooks, so if you want to reproduce or want to find the original code you could find it here:<br>
<a href="https://github.com/chenghuige/Google-American_Sign_Language_Fingerspelling_Recognition" target="_blank">https://github.com/chenghuige/Google-American_Sign_Language_Fingerspelling_Recognition</a> </p>
<p>Sure, will be avaliable soon.</p>
<blockquote>
<p>how long did you spend completing one epoch using 1 4090 GPU?<br>
For 17 layer model(model_size: 63.94M num_params: 16M) and batch size 128, with torch.compile and train data only(no sup data) 1 epoch(num_train_examples: 52163 num_steps_per_epoch: 407) cost about 1min,<br>
so for train data only 300 epochs will use about 5 hours.</p>
</blockquote>
<p>Thanks Dieter! Can not wait to learn from your solution, really big gap, I think there are some major points no other teams have found😀</p>
<p>Yes this affect much, but Chris's method might be even better.</p>
<p>Yes, I'm still very confused why tf so slow on this problem using gpu….</p>
<p>I tried public notebooks of seq2seq and ctc in tensorflow at first, then I convert the ctc notebook to torch, at the last month I change to use conformer and switch to suqeezeformer at the last week.</p> |
Google - American Sign Language Fingerspelling Recognition | [429th Solution] Google - American Sign Language Fingerspelling Recognition - own, native) | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hello. I had the opportunity to describe my decision and the path by which I came to it) I decided not to deny myself the pleasure of taking this opportunity) Unfortunately, I no longer remember which options I chose for the final submission (I got confused in the list of submitted materials) and it probably doesn't matter considering, that this is a description of the solution that took 429th place. I did a lot of experiments, redid the n-th number of layers, tried to assemble something worthwhile out of them - it helped me become 429) Keras - interesting. Thanks to the organizers for a good time.</p>
<h2><strong>Context</strong></h2>
<p>Business context: <a href="https://www.kaggle.com/competitions/asl-fingerspelling/overview" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/overview</a><br>
Data context: <a href="https://www.kaggle.com/competitions/asl-fingerspelling/data" target="_blank">https://www.kaggle.com/competitions/asl-fingerspelling/data</a></p>
<h2><strong>Overview of the Approach</strong></h2>
<p>In the beginning, I worked with two publicly available, well-known approaches (thanks to their authors). I was able to achieve cv 0.9+ with an encoder-decoder transformer by adding some LSTM or DepthwiseConv1D+ConvLSTM1D layers before the classifier, but all my attempts to convert and complete the tflite model ended in failure.</p>
<p>The result of this work was a search and an attempt to create a custom LSTM layer. Somewhere on GitHub, I found a variant of a simple LSTM layer (AI Summer link below). Converting it to keras was the start. The created layer did not lead to the desired result, but laid the foundation for an interesting search process. Everything that was - corresponded in Keras. No less amusing was the combination of everything that was, with new finds.</p>
<p>My experiments are based on the work of Rohith Ingilela's and MARK WIJKHUIZEN Loading, data processing, model output, minus my little additions are their activities.</p>
<h2><strong>Details of the submission</strong></h2>
<p>Once again, I note that I no longer remember which variants were selected by me in the end. I do not exclude that it could even be variants based on the above-mentioned works - pardom. Here are a couple of options for the layers that I used. As I understand it, something similar is often used in work on the classification of poses.</p>
<p>Simple LSTM layer:</p>
<pre><code> :
def :
super(Cell_AI_SUMMER, self).
self.input_length = input_length
self.linear_forget_w1 = tf.keras.layers.
self.linear_forget_r1 = tf.keras.layers.
self.sigmoid_forget = tf.keras.activations.sigmoid
self.linear_gate_w2 = tf.keras.layers.
self.linear_gate_r2 = tf.keras.layers.
self.sigmoid_gate = tf.keras.activations.sigmoid
self.linear_gate_w3 = tf.keras.layers.
self.linear_gate_r3 = tf.keras.layers.
self.activation_gate = tf.keras.activations.tanh
self.linear_gate_w4 = tf.keras.layers.
self.linear_gate_r4 = tf.keras.layers.
self.sigmoid_hidden_out = tf.keras.activations.sigmoid
self.drop_forget = tf.keras.layers.
self.activation_final = tf.keras.activations.tanh #gelu #tf.keras.activations.tanh
def forget(self, x, h):
x = self.linear
x = self.drop
h = self.linear
h = self.drop
return self.sigmoid
def input:
x_temp = self.linear
x_temp = self.drop
h_temp = self.linear
h_temp = self.drop
i = self.sigmoid
return i
def cell:
x = self.linear
h = self.linear
x = self.drop
h = self.drop
k = self.activation
g = ki
c = fc_prev
c_next = g + c
return c_next
def out:
x = self.linear
h = self.linear
return self.sigmoid
def call(self, x, tuple_in ):
(h, c_prev) = tuple_in
i = self.input
f = self.forget(x, h)
h = tf.cast(h, dtype=tf.float32)
c_prev = tf.cast(c_prev, dtype=tf.float32)
c_next = self.cell
o = self.out
h_next = oself.activation
return h_next, c_next
</code></pre>
<p><code>zero_core = 128</code></p>
<pre><code> (tf.keras.Model):
():
(Sequence2, self).__init__(name=)
self.input_length = input_length
self.rnn1 = Cell_AI_SUMMER(, input_length)
self.rnn2 = Cell_AI_SUMMER(, input_length)
self.add = tf.keras.layers.Add()
self.linear = tf.keras.activations.gelu
():
outputs = []
h_t = tf.zeros([zero_core, self.input_length], dtype=tf.double, name=)
c_t = tf.zeros([zero_core, self.input_length], dtype=tf.double, name=)
h_t2 = tf.zeros([zero_core, self.input_length], dtype=tf.double, name=)
c_t2 = tf.zeros([zero_core, self.input_length], dtype=tf.double, name=)
h_t, c_t = self.rnn1(, (h_t, c_t))
h_t2, c_t2 = self.rnn2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
i (future):
h_t, c_t = self.rnn1(, (h_t, c_t))
h_t2, c_t2 = self.rnn2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
outputs = self.add(outputs)
outputs = self.add([outputs, ])
outputs
</code></pre>
<p>Simple Custom Layer:</p>
<pre><code> :
def :
super(Convs, self).
self.input_length = input_length
self.ch1, self.ch2, self.ch3 = , , #, ,
self.conv_0 = tf.keras.layers.
self.conv_1 = tf.keras.layers.
self.conv_2 = tf.keras.layers.
self.conv_3 = tf.keras.layers.
self.conv_4 = tf.keras.layers.
self.conv_5 = tf.keras.layers.
self.conv_6 = tf.keras.layers.
self.conv_7 = tf.keras.layers.
self.batch1 = tf.keras.layers.
self.batch2 = tf.keras.layers.
self.batch3 = tf.keras.layers.
self.batch4 = tf.keras.layers.
self.relu = tf.keras.layers.
self.add = tf.keras.layers.
self.drop = tf.keras.layers.
self.max2 = tf.keras.layers.
self.uns = tf.keras.layers.
self.ave = tf.keras.layers.
def conv0(self, x):
x = self.conv
x = self.batch1(x)
x = self.relu(x)
x = self.conv
x = self.drop(x)
x = self.max2(x)
return x
def conv1(self, x):
x = self.conv
x = self.batch2(x)
x = self.relu(x)
x = self.conv
x = self.drop(x)
x = self.uns(x)
return x
def conv2(self, x):
x = self.conv
x = self.batch3(x)
x = self.relu(x)
x = self.conv
x = self.drop(x)
x = self.max2(x)
return x
def conv3(self, x):
x = self.conv
x = self.batch4(x)
x = self.relu(x)
x = self.conv
x = self.drop(x)
return x
def call(self, input):
out = self.conv0(input)
out = self.conv1(out)
out = self.conv2(out)
out = self.conv3(out)
out = self.add()
return out
</code></pre>
<p>Model example (this is just one of the smaller options):</p>
<pre><code>def get:
inp = tf.keras.
x = tf.keras.layers.(inp)
x = tf.keras.layers.(x)
x = tf.keras.layers.(x)
pe = tf.cast(positional, dtype=x.dtype)
x = x + pe
x = (x)
x = (x)
x1 = (x)
x = (x)
x = tf.keras.layers.()
x = (x)
x = (x)
x = tf.keras.layers.(x)
model = tf.keras.
return model
</code></pre>
<h2><strong>Which led to an improvement.</strong></h2>
<p>Augmentations at the initial stage. Subsequently, I abandoned them.<br>
Alternating UpSampling1D and MaxPooling1D in custom layers.<br>
Replacing Add with Average.<br>
Leaving in the model a certain amount of Conv1DBlock, TransformerBlock from the 1st place solution of the last competition, by HOYSO48<br>
What I didn't think to do)</p>
<h2><strong>Sources</strong></h2>
<p>My sincere respect to the authors of the following works:<br>
<a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference" target="_blank">https://www.kaggle.com/code/markwijkhuizen/aslfr-transformer-training-inference</a><br>
<a href="https://github.com/The-AI-Summer/RNN_tutorial/blob/master/cutom_LSTM.py" target="_blank">https://github.com/The-AI-Summer/RNN_tutorial/blob/master/cutom_LSTM.py</a><br>
<a href="https://www.kaggle.com/competitions/asl-signs/discussion/406978" target="_blank">https://www.kaggle.com/competitions/asl-signs/discussion/406978</a><br>
<a href="https://www.kaggle.com/code/irohith/aslfr-preprocess-dataset-tfrecords-mean-std" target="_blank">https://www.kaggle.com/code/irohith/aslfr-preprocess-dataset-tfrecords-mean-std</a></p>
<p>Something like this. Thanks again for an interesting challenge. Have a good day.</p> |
Google - American Sign Language Fingerspelling Recognition | [4th Place Solution] Conformer Encoder-Decoder Ensemble with beam search and edit_dist optimization | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>The idea is to disrupt the model's training, so it does less memorization of training data and more generalization. Ideally this should make the train score go down but the test score go up.</p>
<p>The flip left right augmentation that I used, mirrors the whole body and reassigns the data so that left hand becomes right hand, left body becomes right body etc. It only makes it look like the sign was made with the other hand. Since most of the data is right-handed this helped improve left-handed predictions.</p>
<p>Similar to what <a href="https://www.kaggle.com/baohaoliao" target="_blank">@baohaoliao</a> said: during training with cross entropy the model always receives perfect input phrases. There are never any wrong predictions in the tokens leading up to the current one. However, during inference predictions are made autoregressively which will make mistakes (if only for missing data). This can disrupt its predictions quite a bit and the augmentation is supposed to help with that. Another similar method I and some competitors tried is masking parts of the token input, which follows a similar logic.</p>
<p>Thanks to Kaggle and the organizer for running this competition! It was a quite unique challenge and even after three months of optimizing it feels like there are still so many things to improve, which is quite special in my opinion.</p>
<h2>TLDR</h2>
<p>My solution is an ensemble of two encoder-decoder models. The encoder is a 12 layer adapted conformer and the decoder is a two layer regular transformer. I added various augmentations and training techniques to align the training objective with the edit_distance competition metric. For decoding I implemented a (cached) beam search for TFLite.</p>
<h2>Challenge and plan</h2>
<p>The goal of the competition was to translate sign language spelling from videos that were preprocessed with human pose recognition. Submissions were made as TFLite models with a limited OPs set and evaluated using the Levenshtein Edit Distance.</p>
<p>These choices had a couple of implications for modelling:</p>
<ul>
<li>"honest" predictions are often not edit-distance-optimal, esp. when the model recognizes no characters in a phrase,<br>
the honest prediction "" achieves a score of 0.0 while "2 a-e -aroe" scores 0.16,<br>
see <a href="https://www.kaggle.com/code/anokas/static-greedy-baseline-0-157-lb" target="_blank">Anoka's Static Greedy Baseline</a></li>
<li>TFLite models in this competition only allowed a very restrictive ops-set, which meant for example that all the native<br>
implementations of beam_search and similar algorithms were not supported</li>
<li>there were time and size limitations to the model (40MB) causing where to "spend" your parameters becoming a major<br>
design decision</li>
<li>the datasets contained quite a few samples where most or all data was missing</li>
</ul>
<p>With these things in mind, I assumed "making things up" would be a significant part of good predictions and<br>
encoder-decoder architectures seemed naturally aligned to this. Additionally having a decoder abstracts away one of the time dimensions which made developing downstream algorithms like beam search or ensembling easier. My early tests also suggested encoder-decoders to work slightly better than CTC, so I went with that architecture.</p>
<h2>Data</h2>
<p>My model used 214 inputs: 21 LHand, 21 RHand, 25 Pose, 1 Nose and 40 Lips points, each using x- and y-coordinates. Data was normalized, NaNs zero-filled and the deltas to t-1 and t-2 values were used as additional Features. During training a maximum of 500 frames was used with longer sequences being resized.</p>
<p>I applied quite a few data augmentations:</p>
<ul>
<li>Flip left-right</li>
<li>Resample along the time dimension</li>
<li>Scale / Translate / Rotate</li>
<li>Mask up to 60% of all frames (worked better than masking sequences)</li>
<li>Spatial cutout (similar to <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">Hoyso48's 1st place solution</a>) <br></li>
</ul>
<p>All of these made a significant impact.</p>
<p>On top of that I transformed the tokens too. I used the fact that when replacing a single token in a phrase with a random token, the ground truth is still an edit-distance-optimal target. This change gave a quite nice boost of +0.008 (using smaller models). I also added single token deletions and insertions but they had a minor impact (if at all).</p>
<p>I split the data five-fold and most of my experiments used only one fold to train with smaller models due to compute restrictions.</p>
<h2>Model</h2>
<p>The base of my model was a deep <a href="https://arxiv.org/pdf/2005.08100.pdf" target="_blank">Conformer</a> encoder followed by a two-layer transformer decoder. The encoder used twelve layers with dimension of 144. The MHSA had four heads with dim-per-head of 64 and the Convolution used a kernel of size 65.<br>
Like the original formulation the model used two macaron-style feed forwards with an expansion factor of four. I made some additional small changes, like changing the position of the BatchNorm and adding DropPath to each Submodule of the Conformer. The model used a drop rate of 0.1 almost everywhere, only before the final classifier it used 0.3. Instead of causal padding I used same padding and explicitly zeroed-out the padded parts. </p>
<p>On the decoder side I tested many different configurations but ended up using a very slim, two layer transformer<br>
decoder. It used four attention heads with dim-per-head of 32 and a feed forward with expansion factor of only two. This was the smallest configuration that I could train without significant performance drop off. Using a small decoder was important since the autoregressive decoding is very performance intensive.</p>
<h2>Training</h2>
<p>A full training run for a single twelve layer encoder model took around two days on my local 3090. To experiment with different architectures, augmentations etc., I only trained shallower models on ~20% of the data for most of the competition.<br></p>
<p>The final training used a cross entropy loss and RAdam optimizer (but AdamW with warmup worked pretty much the same) with a peak lr of 1e-3 and cosine schedule. Weight decay of 2e-6 and label smoothing 0.2 (very minor effect) were used for regularization in combination with light gaussian weight noise (had similar effect as AWP in my test, but lower overhead). I trained for 300 epochs, the first 100 of which used the supplemental data.<br></p>
<p>I used minimum word error rate training after the model finished training. Where character-based edit distance is used as "word error rate". The method starts with a converged model and uses beam search to generate say the top four predictions. It then calculates each prediction's edit distance and uses this as a weight for the model's predicted probabilities. See for example <a href="https://arxiv.org/abs/1712.01818" target="_blank">Minimum Word Error Rate Training for Attention-based Sequence-to-Sequence Models</a>. The method's results are unstable even after optimizing it quite a bit. However, short training runs of 1-5 epochs gave very considerable gains in early testing. Unfortunately on the final large, ensembled model it was a rather modest improvement of 0.001-0.002.</p>
<h2>Beam search and inference-time optimizations</h2>
<p>Using an ensemble of two models, it was easy to reach the 40MB model size limit. To max out the run time dimension too, I implemented a beam search algorithm that is compatible with the restricted TFLite ops set of this competition. Using it with cached autoregressive decoding allowed me to use beam sizes of five to six (with six sometimes failing the 5h limit). This resulted in + 0.005 on the final ensemble (and even more on earlier, weaker models). The implementation was a bit tricky as there are a few edge cases like having to reorder the decoding caches when beams are changed etc. To prevent the early termination problem when decoding with beam search I used a linear length penalty of 0.15.<br></p>
<p>On top of this I realized my model achieved an edit distance of 0.0 on low information samples (e.g. < 50 frames and < 5 frames with any hand showing). But we knew that a greedy prediction of e.g. "2 a-e -aroe" gets a score of 0.16. Since most of these low information samples seem entirely corrupted, I simply replace the model's predictions on these with a constant prediction. I used " a-e -are", which slightly different from the greedy one mentioned before as I optimized it towards shorter, low information sequences.<br><br>
In the end, adding this one line:</p>
<p><code>x = tf.cond(num_frames < 50 and num_hand_frames <= 3,
lambda: tf.constant([[59, 0, 32, 12, 36, 0, 12, 32, 49, 36, 60]]),
lambda: tf.identity(x))</code></p>
<p>gave an improvement of +0.005 across the board (local eval, private and public LB for all models). Which is as much as the whole beam search …</p>
<h2>What worked and didn't</h2>
<ul>
<li>Beam search gave a decent +0.005 improvement</li>
<li>Replacing the model's prediction on corrupt data samples with a constant default prediction gave +0.005</li>
<li>Deeper models worked better than wider ones</li>
<li>MWER-training gave a small improvement (+0.001 - +0.002) - however, this was with beam search k=5, with greedy decoding gains were larger (+0.005 in local eval)</li>
<li>Replacing a single input token with a random one was a decent augmentation</li>
<li>CTC didn't help as an auxiliary loss</li>
<li>masking decoder input did not help (when random token replacement was used)</li>
<li>z-coordinates did not help</li>
</ul>
<p>As always: really looking forward to reading everyone's solutions. Let me know if there are any questions. Code coming <em>soon</em>.</p> |
Google - American Sign Language Fingerspelling Recognition | [5th place solution] Vanilla Transformer, Data2vec Pretraining, CutMix, and KD | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>No I didn't try.</p>
<p>Yes I used both train and supplemental datasets with equal frequencies. Here is a graph:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2160097%2F15ca15be596182e8928ad95134dbe875%2F2023-08-25%20185714.png?generation=1692957713066386&alt=media" alt=""></p>
<p>And Transformer 24L 256d (36MB) achieved CV 0.82 w/o pretraining while 9L 384d (31MB) achieved CV 0.80.</p>
<p>Data2vec pretraining was the most important technique for me. The vanilla transformer model couldn't achieve high performance without pretraining. For the fair comparison, I tested on Transformer 9L 384d.</p>
<ul>
<li>From Scratch: CV 0.74</li>
<li>w/ Data2vec Pretraining: CV 0.80</li>
</ul>
<p>And training from scratch was more vulnerable to the overfitting.</p>
<p>Thanks to Kaggle and competition hosts for this incredible and meaningful competition. Here is my solution.</p>
<p>The code is available at <a href="https://github.com/affjljoo3581/Google-American-Sign-Language-Fingerspelling-Recognition" target="_blank">the github repository</a>.</p>
<h2>TL;DR</h2>
<ul>
<li>Using hands, pose, and lips landmarks with 3D-based strong augmentation</li>
<li>Vanilla transformer with conv stem and RoPE</li>
<li>Data2vec 2.0 pretraining</li>
<li>CTC segmentation and CutMix</li>
<li>Knowledge distillation</li>
</ul>
<h2>Data Processing</h2>
<p>I used 3d landmark points instead of 2d coordinate because it looks like applying rotation augmentation on 3d space makes models to be more robust. According to <a href="https://developers.google.com/mediapipe/api/solutions/java/com/google/mediapipe/tasks/components/containers/NormalizedLandmark" target="_blank">the mediapipe documentation</a>, the magnitude of z uses roughly the same scale as x. Since x and y are normalized by width and height of camera canvas and they are recorded on smartphone devices, I have to denormalize the landmarks with original aspect ratio to apply correct rotation transform. I simply estimate the aspect ratio by solving affine matrix that maps to the normalized hands at each frame to the standard hand landmarks and get scale factors from the affine matrix. The average aspect ratio is <code>0.5268970670149133</code> and I simply multiply <code>1.8979039030629028</code> to the normalized y values, i.e., <code>points *= np.array([1, 1.8979039030629028, 1])</code>.</p>
<p>Correct Rotation Transform:<br>
$$X' = SRX$$</p>
<p>Wrong Rotation Transform:<br>
$$X' = RSX$$</p>
<p>It's important to note that applying rotation after normalizing coordinates is incorrect. Denormalize, rotate, and then normalize again. Actually, I did not normalize again because it is not necessary.</p>
<p>For inputs, I utilized landmarks from the left hand, right hand, pose, and lips. Initially, I focused solely on hand landmarks for the first few weeks and achieved a public LB score of 0.757. I believed fingerspelling is totally related to hand gestures only. Surprisingly, incorporating auxiliary landmarks such as pose and lips leads better performance and helped mitigate overfitting. The inclusion of additional input points contributed to better generalization.</p>
<p>Here's a snippet of the data augmentation code I employed for both pretraining and finetuning:</p>
<pre><code>Sequential(
LandmarkGroups(Normalize(), lengths=(, , )),
TimeFlip(p=),
RandomResample(limit=, p=),
Truncate(max_length),
AlignCTCLabel(),
LandmarkGroups(
transforms=(
FrameBlockMask(ratio=, block_size=, p=),
FrameBlockMask(ratio=, block_size=, p=),
FrameBlockMask(ratio=, block_size=, p=),
),
lengths=(, , ),
),
FrameNoise(ratio=, noise_stdev=, p=),
FeatureMask(ratio=, p=),
LandmarkGroups(
Sequential(
HorizontalFlip(p=),
RandomInterpolatedRotation(, np.pi / , p=),
RandomShear(limit=),
RandomScale(limit=),
RandomShift(stdev=),
),
lengths=(, , ),
),
Pad(max_length),
)
</code></pre>
<p>The total number of input points is 75. Each component consists of 21, 21, 14, and 40 points, respectively. The hand with more <code>NaN</code> values is discarded and only the dominant hand is selected. As seen in the snippet above, spatial transformations are applied separately to the components. The landmark groups are first centered and normalized by maximum x-y values of each group. Note that z-values can exceed 1.</p>
<h2>Model Architecture</h2>
<p>I employed a simple Transformer encoder model similar to ViT. I used PreLN and rotary position embeddings. I replaced ViT's stem linear patch projection with a single convolutional layer. This alternation aimed to enable the model to capture relative positional differences, such as motion vectors, from the first convolutional layer. With the application of rotary embeddings, there is no length limit and also I didn't truncate input sequences at inference time. Similar to other ViT variants, I also integrated LayerDrop to mitigate overfitting.</p>
<h2>Data2vec 2.0 Pretraining</h2>
<p>Given that the inputs consist of 3d points and I used a normal Transformer architecture which has low inductive bias toward data attributes, I guessed it is necessary to pretrain the model to learn all about data properties. The <a href="https://arxiv.org/abs/2212.07525" target="_blank">Data2vec 2.0</a> method, known for its remarkable performance and efficiency across various domain, seemed promising for adaptation to landmark datasets.</p>
<p><img src="https://i.ibb.co/KLM8LYh/FigureA.png" alt="FigureA"></p>
<p>According to the paper, using multiple different masks within the same batch helps convergence and efficiency. I set $M = 8$ and $R = 0.5$, which means 50% of the input sequences are masked and there are 8 different masking patterns. After I experimented many various models, and I arrived at the following final models:</p>
<ul>
<li>Transformer Large (24L 1024d): 109 epochs (872 effective epochs)</li>
<li>Transformer Small (24L 256d): 437 epochs (3496 effective epochs)</li>
</ul>
<p>Termination of the overall trainings was determined by training steps, not epochs, resulting in epochs that are not multiples of 10. After pretraining the model, the student parameters are used for finetuning.</p>
<h2>CTC Segmentation and CutMix</h2>
<p>Before explaining the finetuning part, it is essential to discuss CTC segmentation and CutMix augmentation. Check out <a href="https://github.com/lumaku/ctc-segmentation" target="_blank">this repository</a> and <a href="https://pytorch.org/audio/main/tutorials/forced_alignment_tutorial.html" target="_blank">this documentation</a> which provide information about CTC segmentation. To summarize, a CTC-trained model can detect the position of character appearances, enabling the inference of time alignment between phrases and landmark videos.</p>
<p>Initially, I trained a Transformer Large model and created pseudo aligned labels. Using the alignments, I applied temporal CutMix augmentation which cuts random part of the original sequence and inserts a part from another random sequence at the cutting point. This technique significantly reduces overfitting and improves the performance approximately +0.02. Furthermore, I retrained the Transformer Large model with CutMix and pseudo-aligned labels like noisy student, and it achieved better performance on CV set.</p>
<p>Moreover, I observed that while supplemental datasets without CutMix degrades the performance, they provided substantial enhancement when used with CutMix, resulting in an improvement of about +0.01 on both CV and LB.</p>
<h2>Finetuning and Knowledge Distillation</h2>
<p>The finetuning phase followed a standard approach. I simply utilized the CTC loss with augmentations mentioned above. Given the constraints of 40MB and 5 hours, the Transformer Large model was too extensive to be accommodated. I explored various combinations and parameter sizes, eventually setting on the Transformer Small (24L 256d) architecture. To compress the Large model into the Small model, I used knowledge distillation like DeiT to predict the hard prediction label from teacher model. I observed sharing same head for KD and CTC adversely affected the performance, so I used distinct heads. I also experimented with RNN-like heads (especially stacked BiLSTM) but there is no performance gain. It seems the model converges fast, but final performance is not changed.</p>
<p><img src="https://i.ibb.co/qp1R3pZ/FigureB.png" alt="FigureB"></p>
<p>The training epochs were as follows:</p>
<ul>
<li>Transformer Large (24L 1024d): 65 epochs</li>
<li>Transformer Small (24L 256d): 830 epochs</li>
</ul>
<h2>CV vs LB</h2>
<p>Contrary to the standard validation strategy (GroupKFold) that many people used, I simply split 5% of the training set to validate the model performance.</p>
<pre><code>train_test_split(train_labels, test_size=, random_state=)
</code></pre>
<p>While I initially employed group kfold based on participant IDs, I encountered incongruities between cross-validation and public LB scores. The approach outlined above led to consistent improvements in both cross-validation and public LB performance.</p>
<p><img src="https://i.ibb.co/DWVG0qF/FigureC.png" alt="FigureC"></p>
<h2>What Didn't Work & Future Work</h2>
<ul>
<li>Using external datasets did not work. Actually, I realized competition dataset is quite large and it was really hard to find large scale fingerspelling set as this competition one.</li>
<li>Although prefix beam search showed a modest enhancement of +0.002 even with a small beam size, my implementation in tflite version is too slow, and I didn't use it finally.</li>
<li>I experimented with various head architectures, but a single linear layer was sufficient.</li>
<li>Conformer and transformer encoder-decoder models were not better than vanilla transformer.</li>
<li>I also tried RandAugment and TrivialAugment but hand-crafted strong augmentations worked well.</li>
</ul>
<p>I had never encountered the error related to coordinator_address before. I'll check about that.</p>
<p>Thanks! I've just noticed that I forgot to include the preprocessing code. I have now made the necessary updates, and you can find the revised code <a href="https://github.com/affjljoo3581/Google-American-Sign-Language-Fingerspelling-Recognition/blob/main/resources/competition/extract_and_normalize_landmarks.ipynb" target="_blank">here</a>.</p> |
Google - American Sign Language Fingerspelling Recognition | [The 11th place] Shallow encoder-decoder model also works | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Yes, it helps, about + 0.005.</p>
<p>Acknowledgments for the great public notebooks:<br>
[1] <a href="https://www.kaggle.com/code/markwijkhuizen/aslfr-eda-preprocessing-dataset" target="_blank">MARK WIJKHUIZEN's data preprocessing notebook </a><br>
[2] <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406684" target="_blank">HOYSO48's first place notebook from ISLR</a></p>
<p>Reproducible Codes:</p>
<ol>
<li><a href="https://www.kaggle.com/code/baohaoliao/aslfr-data-preprocessing" target="_blank">Data preprocessing notebook</a></li>
<li><a href="https://github.com/BaohaoLiao/aslfrv4" target="_blank">Training codes</a>: I need some time to clean it and will guide you in the following. In case someone can't wait to check it.</li>
</ol>
<h1>Data preprocessing</h1>
<p>My data preprocessing and split notebook is based on [1]. The differences are:</p>
<ol>
<li>I used the same landmarks (only x and y) from [2].</li>
<li>I split data based on unique phrases into 10 folds, and use the first fold as the validation set. There are no shared phrases in different folds. For data splitting, I found unique phrase split = random split > participant id split.</li>
<li>Use the same way to preprocess the supplementary data.</li>
</ol>
<h1>Data augmentation (<a href="https://github.com/BaohaoLiao/aslfrv4/blob/main/mask/datav2_distributed.py" target="_blank">file</a>)</h1>
<p>I almost used the same data augmentation and hyper-parameters as [2]. The main differences are:</p>
<ol>
<li>I randomly concatenated two samples with a prob of 50%. I found it useful for overfitting.</li>
<li>For the input to the decoder, I randomly (20%) replaced some ground-truth characters with random characters from the vocab. I apply this trick to avoid exposure bias.</li>
</ol>
<h1>Model architecture (<a href="https://github.com/BaohaoLiao/aslfrv4/blob/main/auto_ctc/conformerencoder_transformerdecoder_mask_droppath_ctc.py" target="_blank">file</a>)</h1>
<p>I use Conformer as the encoder and the vanilla Transformer decoder. Conformer is better than the vanilla Transformer encoder, since it focuses on both local and global relations. The main highlights here are:</p>
<ol>
<li><p>I use both CTC loss and cross-entropy loss. After the encoder, the CTC loss is applied to the encoder output. And cross-entropy loss is applied to the decoder output. The interpolation weights for these two losses are 0.2 for CTC loss and 0.8 for cross-entropy loss. The benefits of this setting are: (1) One trained model can be used in two ways, either non-autoregressive generation with the encoder or autoregressive generation with the decoder. In the end, both generations achieved the same 0.791 public LB, (2) One loss could be a regularization term to the other. When you only want to do non-autoregressive generation, you can throw away the decoder parameters, which allows you to use more parameters during training.</p></li>
<li><p>The hyper-parameters are: 5-layer encoder with hidden_dim=384, mlp_dim=1024, conv_dim=768, num_heads=6, 3-layer decoder with hidden_dim=256, mlp_dim=512, num_heads=4. </p></li>
</ol>
<h1>Three-phase training (<a href="https://github.com/BaohaoLiao/aslfrv4/blob/main/train_cnnencoder_transformerdecoder_mask_ctc_distributed.py" target="_blank">file0</a> and <a href="https://github.com/BaohaoLiao/aslfrv4/blob/main/train_cnnencoder_transformerdecoder_mask_ctc_awp_distributed.py" target="_blank">file1</a>)</h1>
<p>All training uses AdamW, inverse square root schedule, weight decay=0.001 and max norm=5, lr=5e-4, batch size=512, warmup ratio=0.2, label smoothing=0.1, frame_length=368.</p>
<ol>
<li>For the first phase, I only train on the training set and exclude the validation set with #epoch=100.</li>
<li>For the second phase, I include all training data and supplemental data for another 150 epochs.</li>
<li>For the third phase, I use AWP with awp_delta=0.2 and awp_eps=0 on all training data for 300 epochs. AWP is good for generalization, better than rdrop for my case.</li>
</ol>
<h1>What doesn't work</h1>
<ol>
<li>BPE: I try to use subwords rather than characters, but it doesn't work.</li>
<li>Too wide but shallow model: For the abovementioned model, I quantize the model in FP16. The number model's parameters are about 18M, 37MB. We can use about 40M parameters if we use dynamic quantization. But dynamic quantization slows down the inference speed. For your reference, my FP16 CTC model runs 2h30m, while the dynamic quantized one runs about 4h. There is only 0.001 LB performance drop for the dynamic quantized one. Nothing drops from FP32 to FP16. In the last week, I tried to use an 8-layer encoder and a 4-layer decoder (same dimension as above). But I have to use frame_length=100 to reduce the inference time within 5 hours. The results are not good. I think there might be some overfitting with such a larger model.</li>
<li>Ensemble between encoder and decoder: My model could do both autoregressive and non-autoregressive generation at the same time. I first generate the output with the encoder, and do an average on the probabilities of the autoregressive and non-autoregressive output at each time frame. But the result stays the same.</li>
<li>Other data: I used <a href="https://home.ttic.edu/~klivescu/ChicagoFSWild.htm#download" target="_blank">ChicagoFSWild and ChicagoFSWild+</a>, it doesn't help. Domain shift is the main reason.</li>
</ol>
<h1>What could make my model better</h1>
<ol>
<li>Inspired by other top-rank methods, including pose landmarks and z coordination might be better.</li>
<li>Use a deeper but narrower model.</li>
</ol>
<p>For efficiency, I didn't train from scratch when trying something new. I always take the best-performed checkpoint from the latest trial. So I can't give you a certain answer. </p> |
Google - American Sign Language Fingerspelling Recognition | 🥈27th Place Solution🥈 | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - American Sign Language Fingerspelling Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>That's right! The first solution suggested "cutting 2 sequences and their corresponding phrases by that percentage and mixing them." Given my belief that combining data after cutting wouldn't enhance performance, I'm really surprised to see an increase of 0.005 points!</p>
<p>Concat augmentation I implemented showed notable performance improvements when utilized between the training and supplementary data, as well as with an increased number of training epochs.</p>
<p>Concatenating 2 random samples from the "train" and "suppl" data (with an augmentation probability of 1.0) resulted in an LB score improvement of 0.009~0.01.</p>
<p>I trained the model using TPUs on colab, and furthermore, I was able to achieve faster training speeds by using the CTC loss on TPU by <a href="https://www.kaggle.com/shlomoron" target="_blank">@shlomoron</a> </p>
<h1>TLDR</h1>
<p>This competition is very similar to speech recognition. Therefore, I attempted new ideas focusing on techniques used in speech recognition. Among them, the most effective ones were <strong>conformer architecture</strong>, <strong>interCTC technique</strong>, <strong>strong augmentation</strong> and <strong>nomasking</strong>.<br>
<br></p>
<h1>Data Processing</h1>
<p>Out of the provided 543 landmarks, I utilized 42 hand data, 33 pose data, and 40 lip data. Input features were constructed by concatenating xy coordinates (drop z) and motion (xy[1:] - xy[:-1]).</p>
<ul>
<li><p>preprocess</p>
<pre><code>def pre:
x = x
x = tf.where(tf.math.is, tf.zeros, x)
n_frames = tf.shape(x)
lhand = tf.transpose(tf.reshape(x, (n_frames, , args.n_hand_landmarks)), (, , ))
rhand = tf.transpose(tf.reshape(x, (n_frames, , args.n_hand_landmarks)), (, , ))
pose = tf.transpose(tf.reshape(x, (n_frames, , args.n_pose_landmarks)), (, , ))
face = tf.transpose(tf.reshape(x, (n_frames, , args.n_face_landmarks)), (, , ))
x = tf.concat(, axis=)
x = x
return x
def decode:
schema = {
'coordinates': tf.io.,
'phrase': tf.io.
}
x = tf.io.parse
coordinates = tf.reshape(tf.sparse., (-, args.input_dim))
phrase = tf.sparse.
augment:
coordinates, phrase = augment
dx = tf.cond(tf.shape(coordinates)>,lambda:tf.pad(coordinates - coordinates, ,]),lambda:tf.zeros)
coordinates = tf.concat(, axis=-)
return coordinates, phrase
</code></pre></li>
</ul>
<p><br></p>
<h1>Augmentation</h1>
<p>Three types of augmentations were applied, each of which significantly influenced CV.</p>
<ul>
<li><p>flip hand(CV improvement : ~0.003)</p>
<pre><code>
def flip_hand(video):
video = tf.reshape(video, shape=(-1, args.n_landmarks, 2))
hands = video[:, :int(2 * args.n_hand_landmarks)]
other = video[:, int(2 * args.n_hand_landmarks):]
lhand = hands[:, :args.n_hand_landmarks]
rhand = hands[:, args.n_hand_landmarks:]
lhand_x, rhand_x = lhand[:, :, 0], rhand[:, :, 0]
lhand_x = tf.negative(lhand_x) + 2 * tf.reduce_mean(lhand_x, =1, =)
rhand_x = tf.negative(rhand_x) + 2 * tf.reduce_mean(rhand_x, =1, =)
lhand = tf.concat([tf.expand_dims(lhand_x, =-1), lhand[:, :, 1:]], =-1)
rhand = tf.concat([tf.expand_dims(rhand_x, =-1), rhand[:, :, 1:]], =-1)
flipped_hands = tf.concat([rhand, lhand, other], =1)
flipped_hands = tf.reshape(flipped_hands, shape=(-1, args.input_dim))
return flipped_hands
</code></pre></li>
<li><p>flip video and phrase(CV improvement : ~0.005)</p>
<pre><code>
():
x = x[]
y = y[]
x, y
</code></pre></li>
<li><p>concat 2 videos and 2 phrases(CV improvement : ~0.01)</p>
<pre><code># videos phrases
def cat_augment(inputs, inputs2):
x, y = inputs
x2, y2 = inputs2
x_shape = tf.shape(x)
x2_shape = tf.shape(x2)
should_concat = tf..uniform(()) <
x_condition = should_concat & (x_shape[] + x2_shape[] < .max_frame)
x = tf.cond(x_condition, : tf.([x, x2], axis=), : x)
y = tf.cond(x_condition, : tf.([y, y2], axis=), : y)
x, y
</code></pre></li>
</ul>
<p><br></p>
<h1>Model</h1>
<p>The model was constructed utilizing the architectures proposed in Conformer. At first, I employed the Conformer code from <a href="https://github.com/TensorSpeech/TensorFlowASR" target="_blank">https://github.com/TensorSpeech/TensorFlowASR</a>. However, by making specific modifications to the code utilized by <a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a> , I successfully implemented the Conformer architecture. This implementation led to an enhancement of 0.008 in the LB score. This improvement is likely due to the removal of residual blocks between Conformer blocks, allowing for the integration of more layers and resulting in improved robustness against overfitting. Furthermore, the incorporation of the interCTC(<a href="https://arxiv.org/abs/2102.03216" target="_blank">paper</a>) contributed to an LB score(~0.005).</p>
<p>Furthermore, as the model's output was computed without masking and a maximum length of 384 was employed for the CTC loss "input-length' variable, using a larger kernel size(=31) effectively conveyed frame information across the 384-length range, resulting in improved performance.</p>
<ul>
<li><p>The overall structure of the model is as follows.</p>
<pre><code>def get:
NUM_CLASSES=
PAD=
inp = tf.keras.)
x = inp
x = tf.keras.layers.(x)
x = tf.keras.layers.(x)
xs =
i range(num_layers):
x = (x)
x = (x)
xs.append(x)
classifier = tf.keras.layers.
x1 = tf.keras.layers.(xs)
x1 = classifier(x1)
x2 = tf.keras.layers.(xs)
x2 = classifier(x2)
return x1, x2
</code></pre>
<p><br></p></li>
</ul>
<h1>Training</h1>
<ul>
<li>Scheduler : lr_warmup_cosine_decay </li>
<li>Warmup Ratio : 0.1 </li>
<li>Optimizer : AdamW </li>
<li>Weight Decay : 0.01</li>
<li>Epoch : 300(last 100 epoch for only train data(not suppl))</li>
<li>Learning Rate : 1e-3 </li>
<li>Loss Function : CTCLoss</li>
</ul>
<p><br></p>
<h1>Didn't Work</h1>
<ul>
<li>masking </li>
<li>adding distance features</li>
<li>mlm pretraining <br>
<br></li>
</ul>
<h1>Code</h1>
<p><a href="https://github.com/siwooyong/Google-American-Sign-Language-Fingerspelling-Recognition" target="_blank">https://github.com/siwooyong/Google-American-Sign-Language-Fingerspelling-Recognition</a><br>
<br></p> |
Google - Fast or Slow? Predict AI Model Runtime | 10th place solution: Fast or Slow with Graph Transformers | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Summary</h2>
<ol>
<li>Intermediate config fusion</li>
<li>Graph transformer based solution</li>
<li>The best lucky model got 0.715 at private LB</li>
</ol>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1212661%2F04febf5cf4f2e15f365b040eeca533d8%2FModel.png?generation=1700325074557958&alt=media" alt=""></p>
<p>Congratulations to everyone on finishing the Fast or Slow competition and a big thanks to my amazing teammate <a href="https://www.kaggle.com/drhabib" target="_blank">@drhabib</a>. After the competition announcement, we were quite excited about seeing quite an interesting problem considered in it. However, a more detailed look has disclosed that the evaluation is performed only on a few graphs, i.e. the evaluation may be very unstable, and the risk of massive two-digit shakeup was significant (I'm curious if organizers performed a config-based split instead of graph one to avoid it?). So we considered this competition as a lottery and spent here only ~1.5 weeks while working on another competition.</p>
<h2>Details</h2>
<p>The approaches frequently considered in <a href="https://arxiv.org/pdf/2008.01040.pdf" target="_blank">the literature</a> are often based either on early or late fusion, i.e. injection of the configuration input is performed either at the very beginning or after collapsing the graph representation into a single embedding vector. However, the first one struggles with computational inefficiency because the computation must be performed for each configuration independently, which results in issues when thousands of configurations are considered with graphs containing tens of thousands of nodes. Meanwhile, the late fusion method loses the node-specific information at the moment of fusion after collapsing all nodes into a single embedding vector, i.e. the model may have a difficult time assigning a particular configuration to the corresponding nodes. </p>
<p><strong>The key idea of our approach is using the intermediate fusion</strong> that provides <strong>a good balance between computational efficiency and the expressiveness of the graph representation at the moment of fusion with configuration input</strong>. Therefore, we may perform training with 1000s configurations and huge (graphs up to 10^4 nodes) at the same time without a significant overhead. The use of a large number of configurations in each batch is critical for sequence ranking losses like listMLE. Meanwhile, at the moment of fusion, the nodes do not collapse into a single embedding vector, and a particular configuration may be directly associated with the nodes.</p>
<h3>Data</h3>
<p>Some of the node features describe the dimensions of data and kernels, and the product of the dimensions may be as large as 10^6. It is not really acceptable for models, and we simply took a log of input features + 3 to have comparable scales. In our experiments, we also tried to extract additional 29 graph features by customizing the organizer's code but got comparable results to just using the base 140 features.</p>
<p>In the layout pipeline instead of storing everything in the RAM, which may be quite large in comparison to tile data, we loaded only graph features (several GB only). Meanwhile, the configs were sampled in chunks of 1000 and loaded during training in a just-in-time manner instead of loading all configurations and using only 1000 of them. It has eliminated the data loading bottleneck.</p>
<h3>Model</h3>
<p><strong>Our model is based on transformers adapted to work effectively with graph data on consumer-grade hardware.</strong> </p>
<p>(Tile) Specifically, the tile model uses a sequence of residual graph blocks, enabling the creation of the local neighborhood representation, before global mixing with self-attention blocks followed by node information retrieval for particular configurations with cross-attention transformer blocks. With this setup training of the model reaching 0.97+ slowdown metric takes under 1 min. The LB of our tile-only model is 0.196 at private and 0.197 at public out of 0.2. The combination of different folds gave 0.196 and 0.198 at private and public LB.</p>
<p>(Layout) In the layout model, we must replace standard dot product attention with multi-head <a href="https://arxiv.org/pdf/2205.14756.pdf" target="_blank">linear attention</a>, which has linear complexity on the number of tokens. This attention enables a global receptive field within the entire 10^4 node graph while being relatively computationally cheap enabling running 12 block transformer on GPUs like 4090 or A6000. We replaced the ReLU nonlinearity in the attention with a more robust ELU+1 function. We do not use SLA in the tile model because of difficulties with masking padding tokens. The MLP part of the transformer blocks, meanwhile, is replaced with graph networks, which enable local mixing of features between neighboring nodes. We considered APPNP, SAGE, GAT, GPRGNN graph modules, with APPNP getting slightly better results. We considered both, unidirectional and bidirectional graph models. In one set of experiments, we also considered 4 and 6 layers <a href="https://arxiv.org/pdf/2301.09474.pdf" target="_blank">DiFFormer model</a>. The graph transformer is followed by pooling of configurable nodes, concatenation of them with the corresponding configurations and mixing with MLP, and finally by global pooling among all configurable nodes and prediction of the overall ranking. The models are illustrated in the plot at the beginning of the post.</p>
<p>With the intermediate fusion approach even relatively wide (n=256) and deep (up to 12 layers) models are very fast, taking just a few seconds per epoch on tile setup, a few minutes per epoch with XLA layouts, and 30 min to 1 hour for NLP layouts while using up to 1000 configurations simultaneously. The convergence takes ~5 epochs for tile models and 16 epochs for layout ones.</p>
<h3>Training</h3>
<p>We used standard for transformers AdamW optimizer, cosine annealing with lr=5e-4, and wd of 1e-2. The training is performed for 5 epochs for tile and for 16 epochs for layout models. In some runs, we used EMA average of weights and gradient accumulation. We used listMLE as the loss function, which was possible because we considered ~1000 configurations for a given graph in each batch.</p>
<p>Since XLA and NLP graphs exhibit a drastic difference in graph size we decided to split them into two separate sets of models trained independently. Specifically, XLA graphs are huge (VRAM hungry) and the number of configs is low. While NLP graphs are quite smaller with a huge number of configs (i.e. longer training). So we could train XLA models with 256 configs per graph on 24 GB VRAM GPUs and 256-1000 configs on 48 GB VRAM GPUs. While NLP models are easily trained with 1000 configs per graph taking less than 24 GB VRAM.</p>
<h3>Evaluation</h3>
<p><strong>Running experiments we quickly realized that evaluation on eval set is not stable, and nearly all considered setups achieved statistically insignificant differences in comparison to reruning the same setup with a different seed.</strong> It did not allow us to assess the real improvement of models under different setups and report the ablation study. </p>
<p>We set an 11-fold split scheme (val set + 10-fold split of train set) to enable sufficient precision of evaluation needed to distinguish small performance differences in the considered setups. However, given only ~1 week remaining for us in the competition and 8-16 hours per fold total training time for NLP layouts, we did not proceed much further with that and ran just a few folds for diversity in several experiments. </p>
<h3>Final model</h3>
<p>Our main strategy in this competition, since we could not reliably assess the performance, was running as many configurations as possible and mixing them together to mitigate the effect of the possible shakeup. We composed 10-20 different configurations for XLA and NLP models. This setup got 0.712 and 0.696 at public and private LB.<br>
In addition, we selected our best public LB submission, which consists of 2 APPNP XLA models and 2 DIFFormer NLP models. It reaches 0.721 at public and 0.703 at private LB. A very surprising result for us. <br>
Our best lucky private LB sub meanwhile, is 0.706 and 0.715 at public and private LB. In this sub we used APPNP models with gated units instead of residual sum.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 11th place solution: LightGBM | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the host and congratulations to the winners.<br>
I'm glad to win my 4th gold medal on this competition.<br>
I did not use GNN, but used LightGBM with feature engineering.<br>
The reason why I chose LightGBM is that I thought that the runtime of the model in a single TPU is equal to the sum of the runtime of each node, and learning the aggregated statistics from the graph would be sufficient to achieve good score without learning the graph structures.</p>
<h2>Layout</h2>
<h3>Features</h3>
<p>I extracted the following features from the graph.</p>
<ul>
<li>Number of nodes of each type for conv/dot/reshape when using the following classification method<ul>
<li>Conv: If any one of the input/output number of dimensions or config values, or the 93~106th values of node_feat is different, it is of a different type</li>
<li>Dot: If any one of the input/output number of dimensions or config values, or the index features of dot operation (extracted from the .pb file on its own) is different, then it is of a different type</li>
<li>Reshape: If any one of the input/output number of dimensions or config values, or the inconsistency on the element products in a set of a certain dimension, then it is of a different type</li></ul></li>
<li>Number of times the element is copied<ul>
<li>Determine if a copy is needed by comparing the layout of each configurable node and the configurable nodes connected to it.</li></ul></li>
<li>Counting binning the size of the 1st/2nd minor dimension</li>
<li>Sum of padding generated at each configurable node</li>
<li>(only default) Occurrence rate of config for each node relative to the total data for that model<ul>
<li>Because genetic algorithms are used in the search, the more frequently a config pattern appears, the faster the config runtime will tend to be.</li></ul></li>
</ul>
<h3>Models</h3>
<p>I trained the pointwise and pairwise models.</p>
<ul>
<li>Pointwise LightGBM<ul>
<li>Target: Normalized rankings(0~1)</li>
<li>Loss: MAE Loss</li>
<li>Public LB: 0.715 (Private LB: 0.680)</li></ul></li>
<li>Pairwise LightGBM<ul>
<li>Loss: Binary</li>
<li>Randomly select the same number of pairs as the number of configurations and generate train/valid.</li>
<li>Inference on test data predicts for all pairs of 1000^2 and then sort configs using the sum of the predictions.</li>
<li>Input features are as follows: <ul>
<li>The features for one config of the pair</li>
<li>The difference between the features of the two configs</li></ul></li>
<li>Public LB: 0.728 (Private LB:0.701)</li></ul></li>
</ul>
<p>I used the same train/valid given by the host. (Failure to devise a better CV may have been the cause of the shake down)</p>
<h2>Tile</h2>
<h3>Features</h3>
<ul>
<li>Config features</li>
<li>Node features averaged over all nodes</li>
</ul>
<h3>Models</h3>
<p>I trained the pointwise LightGBM model.</p>
<ul>
<li>Target: Normalized rankings(0~1)</li>
<li>Loss: MAE Loss</li>
<li>Public LB(only tile): 0.198 (Private LB(only tile): 0.195)</li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | 13th Place Solution for the Google - Fast or Slow? Predict AI Model Runtime Competition | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>13th Place Solution for the Google - Fast or Slow? Predict AI Model Runtime Competition</h1>
<p>This is my solution for the "Fast or Slow? Predict AI Model Runtime" Competition. I hope you find it useful!</p>
<p>The key principles of my approach were to start with something simple and improve it in many iterations, and to work under the hardware constraints that I had (16 GB RAM, 4 GB VRAM).</p>
<h2>Context section</h2>
<ul>
<li>Business context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/overview" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/overview</a></li>
<li>Data Context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/data" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/data</a></li>
</ul>
<h2>Overview of the approach</h2>
<h3>Layout model</h3>
<p>The core idea is to extract features from the graph and its nodes, and train a Multi-layer Perceptron with that information. For each configurable node of the computational graph we took some node properties, the layout used, and properties from its "parents" and "siblings". The "parent" nodes are the ones that produce the node inputs. Two nodes are "siblings" if they share a parent. For example, in the following figure, nodes 1 and 2 are the parents and nodes 3, 5, and 6 are the siblings.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2528048%2F665c76b0456511e708fcdc2859c2ab98%2Fimg_kaggle.jpeg?generation=1701268499581469&alt=media" alt=""></p>
<p>For each configurable node in the graph we had a list of features that were processed by 3 fully-connected layers with dropout layers in between. After that, the "node" dimension was averaged, so all the node information is represented as a vector. Two extra inputs were concatenated to this vector: a "graph description" and the "subset information". The "graph description" is a vector with how many nodes of each type are present in the graph (normalized to sum 1), with an extra value that is the number of nodes of the graph (with a logarithm) to give the model an idea of the graph's size. The "subset information" is a vector that signals if the graph comes from the "xla:default", "xla:random", "nlp:default" or "nlp:random" subset, for what we used an "Embedding" layer of keras.</p>
<p>This new vector was processed by 3 additional fully-connected layers (no dropout this time). The Pairwise Hinge loss was used as objective function during training. In order to do that, each training batch of size 128 had examples of 16 different graphs, with 8 configuration examples each. Each batch is built by randomly choosing a subset with equal probability, so the batches are subset-balanced on average. The final submission was an ensemble of 3 independent training runs. </p>
<h3>Tile model</h3>
<p>The tile model is a simplified version of the layout model. Each configuration is described with a vector that has the "config_feat" information and also a "graph descriptor" (the same one from the layout model). This model is a Multi-layer Perceptron with 3 fully-connected layers and one dropout layer after the first layer. The loss function and batch structure is the same as the layout model, but with a larger batch size (600) and a larger number of configurations per graph (20).</p>
<h3>Validation</h3>
<p>The "valid" folder examples from the dataset were used as the validation set. We performed validation every 10000 training iterations, and we computed the competition metric over that set. In the case of the layout model, the metric was computed for each one of the four subsets and then an average is computed. If the validation metric did not improve after 5 validations, the training is stopped.</p>
<h2>Details of the submission</h2>
<h3>Tile model details</h3>
<p>The "tile problem" was relatively easy in comparison to the layout problem, so we did not spend that much effort improving this model. The number of configurations per graph was limited to 160, and we sampled them giving the configurations with a lower runtime a higher probability (using an exponential distribution), as the challenge here was about finding the fastest configuration, not sorting all the configurations.</p>
<h3>Node features (Layout model)</h3>
<p>From all the available features in the "node_feat" matrices, we selected the ones that we thought were the most important. This helps keeping the required memory low. These features are:</p>
<ul>
<li>shape_dimensions (21-26).</li>
<li>reshape/broadcast dimensions (31-36).</li>
<li>convolution_dim_numbers_input_spatial_dims (95-98).</li>
<li>convolution_dim_numbers_kernel_spatial_dims (101-104).</li>
<li>layout_minor_to_major (134-139)</li>
</ul>
<p>Values in parentheses correspond to the selected indices of "node_feat". We also gave the node layout information and the opcode to the model (encoded as a vector with a keras Embedding layer). Another important thing is that a re-ordered version of the shapes was given to the network according to the layout information (in addition to the original version). </p>
<p>For the siblings we took each sibling output shape, its layout and a boolean that compares the node layout with the sibling layout to check if they are the same. As the competition overview mentioned, if the layouts of two siblings are different, an extra copy operation is needed, so that motivated the creation of this variable.</p>
<p>For the parents we keep their output shapes and physical layouts. We also took the opcodes from the parents and the siblings, and express them as a vector with the help of the Embedding layer of keras.</p>
<h3>Keep the training stable (Layout model)</h3>
<p>To facilitate the training process, all the features that took values across many orders of magnitude (e.g. tensor shapes) were passed to a logarithm to avoid very large input values. The features were scaled using a mean / standard deviation normalization, with some clipping in the std estimation to avoid dividing by a very small value.</p>
<p>A cosine decay schedule was used for the learning rate. After a 10000 iteration linear warm-up in the learning rate, the cosine decay reduced the parameter across 250k iterations until it reached a 5 % of the original value. Adam was used as optimizer, with a clipnorm value of 1.0 to avoid large weight updates.</p>
<p>Many configurations had the same layout. All of them were replaced by just one instance of that layout, and the runtime replaced by the mean of the runtimes.</p>
<h3>Things that didn't work that well…</h3>
<p>We had some instability problems with the List MLE loss, so we chose using the Pairwise hinge loss instead. The problem was that after many iterations, suddenly a NaN value appeared in the model (or loss, idk) and destroyed all the model weights.</p>
<h3>Keeping the training under the memory budget</h3>
<p>As we mentioned, we worked with a limited memory budget of 16 GB of RAM and 4 GB of VRAM, so we had to be very careful of not loading too much data at the same time and be conservative with the model size. The first important thing was to process all the npz files and save the necessary information in the tfrecords format of tensorflow (with file compression activated). During training, these files were read from disk, trying to give the model samples from many different graphs instead of seeing just one graph at a time.</p>
<p>The number of configuration per graph was capped at 7500, and the number of configurable nodes given to the network was capped at 1000. As many different graphs were given to the network and considering that each graph has a different number of configurable nodes, it is necessary to pad and mask tensors to make all the samples the same length across the "node" dimension. This can have a heavy memory burden if the number of used nodes is increased too much, so the number 1000 was chosen given this restriction. I also put a limit in the number of parents (2) and siblings (3) for each node.</p>
<h2>Sources</h2>
<p>Code: <a href="https://github.com/ignacioreyes/kaggle_model_runtime" target="_blank">https://github.com/ignacioreyes/kaggle_model_runtime</a></p>
<p>Embedding layer (tf/keras): <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding" target="_blank">https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding</a></p>
<h4>Note: I wrote many sections in plural, as is customary in academic papers.</h4> |
Google - Fast or Slow? Predict AI Model Runtime | 14th Place Solution for the Google - Fast or Slow? Predict AI Model Runtime Competition | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Context</h1>
<ul>
<li>Business Context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/overview" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/overview</a></li>
<li>Data Context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/data" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/data</a></li>
</ul>
<h1>Overview of Approach</h1>
<h2>Data Preprocessing</h2>
<ul>
<li>Developed 2 graph compression techniques to reduce problem complexity (N-hop reduction from config nodes and a config meta-graph).</li>
<li>Normalized numeric features, dropped features with 0 standard deviation</li>
<li>One-hot encoded opcodes</li>
</ul>
<h2>Feature Engineering</h2>
<ul>
<li>Created several node specific features and config specific features</li>
<li>Created some global features applied to the whole graph</li>
</ul>
<h2>Model Design</h2>
<p>The models all broadly followed the following format:</p>
<ol>
<li>Graph/Config/Opcodes concatenated</li>
<li>Graph representations used to perform some Graph Convolutions (varies slightly between models)</li>
<li>Global Mean Pooling concatenated with Global Features</li>
<li>MLP to output layer</li>
</ol>
<p>The Tile Dataset result was a single model following this design, with 3 GraphSAGE layers and 3 Linear Layers trained with ListMLE loss. The Layout Dataset results were taken from an ensemble of models with slight variations in their design. All models used GeLu activations, but differed in other respects (detailed below). Output losses used were ListMLE and Pairwise Hinge.</p>
<h2>Validation</h2>
<p>We kept the same Train/Val split as provided in the competition dataset.</p>
<h1>Details of Approach</h1>
<h2>Graph Reduction</h2>
<p>Each layout graph was transformed into two distinct graphs:</p>
<ol>
<li>A 3-Hop graph (hops from the Configurable Nodes)<br>
The configurable nodes are the ones that can differ between graphs, so it makes sense that any graph reduction would try to preserve these nodes. An N-Hop graph transformation will retain configurable nodes, and nodes (and edges) up to N hops away from any configurable node. I landed on a 3-hop graph through val scores, but I think we could have gotten better results with 4 or 5 hop graphs given some time to tune.</li>
<li>A "Config Positioning " graph. This graph removed all non-configurable nodes, but drew edges between all configurable nodes where there was a path from one node to another that did not cross another configurable node. My intuition guiding this was that the relative position of a poorly configured node with respect to downstream configurable nodes might have a meaningful impact on its overall contribution to the runtime. <br>
An example of the transformations is shown below (though I just used a 1-hop example).</li>
</ol>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3626485%2F3ecc17ccdeead41cba76a26a6087d03b%2FGraphReductions3.png?generation=1700281118388593&alt=media" alt=""></p>
<h2>The Features</h2>
<p>Before even talking about new features, it's worth mentioning that normalization is absolutely essential on this problem. If you didn't normalize your data, you didn't score well.</p>
<h3>Node Features</h3>
<p>We defined a few extra features. For the nodes, we defined:</p>
<ul>
<li>Shape sparsity (shape sum / shape product)</li>
<li>Dimensionality (count of active shapes)</li>
<li>Stride Interactions</li>
<li>Padding Proportions</li>
<li>Reversal Ratio</li>
<li>Is configurable (obvious)</li>
</ul>
<h3>Configuration Features</h3>
<p>Additional config features were computed for the output, input and kernel sections. Each feature was replicated for each of those sections:</p>
<ul>
<li>is_default (all negative ones)</li>
<li>active_dims (count of non-negative)</li>
<li>max order (largest value)</li>
<li>contiguity rank (count of longest contiguous ordering / active dims)</li>
<li>section variance</li>
</ul>
<p>Additionally, we computed similarity metrics for</p>
<ul>
<li>output-input</li>
<li>output-kernel</li>
<li>input-kernel</li>
</ul>
<h3>Opcodes</h3>
<p>Opcodes were just one-hot encoded.</p>
<h3>Global Features</h3>
<ul>
<li>Longest Path Length in Graph</li>
<li>Average shortest path length between connected components</li>
<li>Number of nodes</li>
<li>is_default</li>
</ul>
<p>The is_default flag was introduced because it <em>seemed</em> like the random vs. default distributions were different enough to warrant having predictive value, since the test set also contained this information. It seemed to provide a small but reliable boost to val scores.</p>
<h2>The Models</h2>
<h4>Layout Models</h4>
<p>For the layout problem, we defined the following GraphBlock, using a GAT with (out channels / 2) channels to process the node features given the 3-Hop Graph, and GAT or GraphSAGE with (out channels / 2) channels to process the features given the Config Positioning graph.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3626485%2F893f9ce0ec19a542d2156afc8e951c66%2FGraphBlock2.png?generation=1700278642575220&alt=media" alt=""></p>
<p>We then layered the GraphBlocks with residual connections and added some dense feed-forward layers (also with residuals) to which we concatenated the global features. The final result was an ensemble of slightly different versions of this model (varying hidden dims, linear layers, etc.). </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3626485%2Fc9cfbe2d9197c006df390155fbaab177%2FModelDiagram.png?generation=1700279330883081&alt=media" alt=""></p>
<p>The code for of multi-edge block used in the Layout Set is shown below (the Tile Set model is very similar, with fewer complicated pieces. It's less polished but you can view it <a href="https://github.com/mattdeak/kaggle-fast-or-slow/blob/master/ml/xla_gcn_v1/model.py" target="_blank">here</a>. The rest of the code is available <a href="https://github.com/mattdeak/kaggle-fast-or-slow/blob/master/readme.md" target="_blank">here</a></p>
<pre><code> (nn.Module):
():
().__init__()
output_dim_per_block = output_dim //
main_block == :
self.main_edge_block = GATBlock(
input_dim,
output_dim_per_block,
heads=heads,
with_residual=,
dropout=dropout,
)
:
self.main_edge_block = SAGEBlock(
input_dim,
output_dim_per_block,
with_residual=,
dropout=dropout,
)
alt_block == :
self.alternate_edge_block = GATBlock(
input_dim,
output_dim_per_block,
heads=heads,
with_residual=,
dropout=dropout,
)
:
self.alternate_edge_block = SAGEBlock(
input_dim,
output_dim_per_block,
with_residual=,
dropout=dropout,
)
self.with_residual = with_residual
self.output_dim = output_dim
():
main_edge_index = data.edge_index
alternate_edge_index = data.alt_edge_index
main_edge_data = Data(
x=data.x,
edge_index=main_edge_index,
batch=data.batch,
)
alternate_edge_data = Data(
x=data.x,
edge_index=alternate_edge_index,
batch=data.batch,
)
main_edge_data = self.main_edge_block(main_edge_data)
alternate_edge_data = self.alternate_edge_block(alternate_edge_data)
f = torch.cat([main_edge_data.x, alternate_edge_data.x], dim=)
self.with_residual:
f += data.x
new_data = Data(
x=f,
batch=data.batch,
)
data.update(new_data)
</code></pre>
<h4>Tile Model</h4>
<p>The Model for the Tile Dataset is more or less exactly the same, except it used 3 graph layers, 3 linear layers, and no graph reduction at all (because there were no configurable node).</p>
<h3>Training Process</h3>
<p>NLP and XLA were trained separately. I would have loved to play with a unified model more, but I ran out of time and compute, and they seemed to learn well when they were separate.</p>
<p>All models used:</p>
<ul>
<li>AdamW Optimizer</li>
<li>Batch Size of 16</li>
<li>GeLu Activations</li>
<li>LayerNorm in both Graph and MLP</li>
<li>Global Mean Pooling after the graph blocks</li>
<li>No Scheduler</li>
</ul>
<p>Other parameters are as follows:</p>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>XLA-1</th>
<th>XLA-2</th>
<th>NLP-1</th>
<th>NLP-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Loss</td>
<td>listMLE</td>
<td>listMLE</td>
<td>listMLE</td>
<td>Rank Margin Loss</td>
</tr>
<tr>
<td>Learning Rate</td>
<td>0.00028</td>
<td>0.00028</td>
<td>0.00028</td>
<td>0.0001</td>
</tr>
<tr>
<td>Weight Decay</td>
<td>0.004</td>
<td>0.004</td>
<td>0.004</td>
<td>0.007</td>
</tr>
<tr>
<td>Graph Layers</td>
<td>4</td>
<td>4</td>
<td>4</td>
<td>4</td>
</tr>
<tr>
<td>Graph Channels</td>
<td>128</td>
<td>128</td>
<td>128</td>
<td>128</td>
</tr>
<tr>
<td>FF Layers</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>FF Channels</td>
<td>128</td>
<td>128</td>
<td>128</td>
<td>64</td>
</tr>
<tr>
<td>3-Hop Graph Conv</td>
<td>GAT(heads=8)</td>
<td>GAT(heads=8)</td>
<td>GAT(heads=8)</td>
<td>GAT(heads=1)</td>
</tr>
<tr>
<td>Config Graph Conv</td>
<td>GAT</td>
<td>GAT</td>
<td>GAT</td>
<td>GraphSAGE</td>
</tr>
<tr>
<td>Dropout</td>
<td>0.15</td>
<td>0.15</td>
<td>0</td>
<td>0</td>
</tr>
</tbody>
</table>
<p>Outputs were collected from XLA-1 after 3 epochs, and 2 snapshots of XLA-2 in training (end of epochs 2 and 3) based on their val scores.</p>
<p>The NLP Models never even finished one epoch, the loss appeared to plateau and I only had so much compute. This indicates to me that I probably could have tuned the LR better or regularized better.</p>
<h3>Ensembling</h3>
<p>For a given file id (e.g "xla:default:abc…"), we have N (1000 or 1001) predictions per model output. We min-max normalize the predictions so they're all in a zero-to-one range, then we just add the scores elementwise for each model output. We use the summed config scores to derive the rank ordering.</p>
<p>The normalization is important here, because the models are not guaranteed to be outputting numbers on the same scale if you're using a ranking loss.</p>
<p>I also tried simple rank averaging and Borda count, both of which worked but not as well as the min-max averaging. This is likely because these methods can't account for things like "how much better is rank 2 than rank 3", while the min-max normalized ensemble can.</p>
<h4>Sources</h4>
<ul>
<li>Graph Attention: <a href="https://arxiv.org/pdf/1710.10903.pdf" target="_blank">https://arxiv.org/pdf/1710.10903.pdf</a></li>
<li>GraphSAGE: <a href="https://arxiv.org/pdf/1706.02216.pdf" target="_blank">https://arxiv.org/pdf/1706.02216.pdf</a></li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | 16th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks for hosting the competition on a very interesting topic and congratulations to all the winners!</p>
<p>I'll share my solution briefly.</p>
<h1>Summary</h1>
<ul>
<li>3-hop subgraphs from configurable nodes</li>
<li>Drop duplicated configs</li>
<li>Listwise loss. In my experiments, listwise loss converged faster and performed better than pairwise loss.</li>
<li>3-layer <code>SAGEConv</code> with <code>LayerNorm</code> and residual connections. I implemented residual connections by simply adding the initial embedding to the output of each layer. Below is a code snippet.</li>
</ul>
<pre><code> ():
node_opcode = batch.node_opcode.long()
opcode_embeds = self.opcode_embedding(node_opcode)
x = torch.concat([batch.node_feat, opcode_embeds, batch.node_config_feat * self.node_config_weights], dim=)
x = self.lin1(x)
x = self.norm1(x).relu()
x_init = x
i (self.n_layers):
x = self.convs[i](x, batch.edge_index)
x = self.norms[i](x).relu()
x = x_init + x
x = torch.concat([global_mean_pool(x, batch.batch), global_max_pool(x, batch.batch)], dim=)
x = self.dropout(x)
x = self.readout(x)
x
</code></pre>
<ul>
<li><p>Models were trained separately for diffrent subtypes</p></li>
<li><p>CV scores (provided train, valid splits)</p>
<ul>
<li>xla default: 0.37</li>
<li>xla random: 0.71</li>
<li>nlp default: 0.55</li>
<li>nlp random: 0.96</li>
<li>tile: 0.97</li></ul>
<p>With these CV scores, I got a score of 0.684 (public) and 0.688 (private). </p></li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | 17th place solution: GNN + TransformerEncoderLayer w/ BCELoss. | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks for hosting the interesting competition and congratulations to the winners!<br>
I was disappointed with the result, but I learned a lot.</p>
<p>only describe T0m part.</p>
<h1>Layout</h1>
<ul>
<li>GNN(SAGEConv) + TransformerEncoderLayer</li>
<li>BCELoss</li>
<li>Predictions were made for all pairs, and the average of the predictions was used as a final guideline for sorting</li>
<li>For tests with graphs similar to train, Lightgbm was used to train and make predictions individually. Only node_config_feat was used in that case.<ul>
<li>This is not the cause of the shake down.</li></ul></li>
</ul>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4705999%2F6520e81b8d8ee65c6b97dbf86ec6f5ce%2F2023-11-20%2014.48.00.png?generation=1700459296767515&alt=media" alt=""></p> |
Google - Fast or Slow? Predict AI Model Runtime | 19th Place Solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>For us using gatv2 did better than sage by quite a margin</p>
<p>Thanks to Kaggle and Google for organizing this competition! This was my first competition and I really enjoyed it. We didn't know anything about GNN's before starting this competition and we learned a lot throughout this competition. I would also like to thank my great teammate <a href="https://www.kaggle.com/roysegalz" target="_blank">@roysegalz</a> </p>
<h3>Tile dataset:</h3>
<p>For the Tile dataset we used an RGCN where the relations are the node_opcode. The model consisted of 4 blocks where a block consisted of RGCN -> LayerNorm -> ReLU</p>
<ul>
<li>loss function - ListMLE</li>
<li>hidden dim = 128</li>
<li>CosineLRScheduler</li>
<li>AdamW</li>
<li>lr = 4e-4</li>
<li>weight decay = 1e-4</li>
<li>max aggr for final graph representation</li>
</ul>
<p>We reached 0.198 on Tile + sample_submission (random predictions on Layout datasets)</p>
<h3>Layout datasets:</h3>
<p>We realized that the best way to differentiate between different graphs is by emphasizing the node_config_feat. We recognized the problem that the number of nodes that contain node configs is relatively small compared to the number of nodes in the graph. Hence we understood that this data might get lost in the model throughout the forward pass. Our way to solve the problem was the following:<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F6061339%2Fc3795f9d4cb3cd838f865260a2433cd1%2FNew%20node%20config%20feat.png?generation=1700264018548073&alt=media" alt=""></p>
<p>First we represent the node_config_feat in a different way (nn.Embedding and one hot vector). After doing that we created this model architecture (which is the most important part of our solution):<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F6061339%2Fd852425e39c06ed17a4d2c822fda94f4%2FLayout%20Architecture.png?generation=1700264126117504&alt=media" alt=""></p>
<p>Concatenating the data again after each block increased our scores dramatically.</p>
<p>We used the same model architecture for all the different layout datasets.</p>
<p>The model consisted of 3 blocks where a block consisted of GATv2-> LayerNorm -> ReLU (We decided not to use RGCN since it was really computationally expensive to run on the layout dataset)</p>
<ul>
<li>hidden dim = 64</li>
<li>loss function - nn.MarginRankingLoss(0.5) </li>
<li>CosineLRScheduler</li>
<li>AdamW</li>
<li>lr = 2e-4</li>
<li>weight decay = 1e-4</li>
<li>Virtual node for final graph representation</li>
</ul>
<p>Our CV Scores:</p>
<table>
<thead>
<tr>
<th>Dataset</th>
<th>Kendal-Tau CV</th>
</tr>
</thead>
<tbody>
<tr>
<td>XLA default</td>
<td>~0.3</td>
</tr>
<tr>
<td>NLP default</td>
<td>~0.5</td>
</tr>
<tr>
<td>XLA random</td>
<td>~0.62</td>
</tr>
<tr>
<td>NLP random</td>
<td>~0.94</td>
</tr>
</tbody>
</table> |
Google - Fast or Slow? Predict AI Model Runtime | 1st Place Solution for the Google - Fast or Slow? Predict AI Model Runtime Competition | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Obrigado Giba! 🙇</p>
<p>Muito obrigado Marília 🙏</p>
<p>Let me know if there is anything I can help clarifying!</p>
<p>Thank you Dmitrii! Congratulation to you and your team as well!<br>
I used a website called <a href="https://app.diagrams.net/" target="_blank">drawIo</a></p>
<p>First of all, thanks Kaggle and Google for hosting this great competition. Also, I'd like to thanks my teammates and friends <a href="https://www.kaggle.com/tomirol" target="_blank">@tomirol</a> and <a href="https://www.kaggle.com/thanhhau097a" target="_blank">@thanhhau097a</a>, which made this journey even more special.</p>
<h1>Context</h1>
<ul>
<li>Business context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/overview" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/overview</a></li>
<li>Data context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/data" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/data</a></li>
</ul>
<h1>TLDR:</h1>
<ul>
<li>We pruned and compressed the layout graphs in order to increase the efficiency of our experiments</li>
<li>We removed duplicated configs for layout</li>
<li>We changed the <code>node_feat</code> to use -1 padding instead of 0</li>
<li>We used the provided <code>train</code>, <code>val</code>, <code>test</code> splits since we found good correlation with LB</li>
<li>Data preprocessing:<ul>
<li>StandardScaler for <code>node_feat[:134]</code></li>
<li>Shared learned embedding (4 channels) for <code>node_feat[134:]</code> and <code>node_config_feat</code></li>
<li>Features are concatenated before first linear</li></ul></li>
<li>Models with the following architecture:<ul>
<li>Linear on the input features</li>
<li>2x graph conv with attention blocks <ul>
<li><code>InstanceNorm</code> -> <code>SAGEConv</code> -> <code>SelfChannelAttetion</code> -> <code>CrossConfigAttetion</code> -> <code>+residual</code> -> <code>GELU</code></li></ul></li>
<li>Global (graph) mean pooling</li>
<li>Linear logit layer</li></ul></li>
<li><code>PairwiseHingeLoss</code> function</li>
</ul>
<h1>Data preparation</h1>
<p>We joined the competition with a bit less than a month to finish, so one of the first problems we tried to tackle was the low efficiency in our training jobs.</p>
<h2>Graph pruning</h2>
<p>For layout, we noticed that only <code>Convolution</code>, <code>Dot</code> and <code>Reshape</code> were configurable nodes. Also, in most cases, the majority of nodes would be identical across the config set. Thus, we opted for a very simple pruning strategy where, for each graph, we would only keep the nodes that were either configurable models themselves or were connected to a configurable node, i.e., input or output to a configurable node. By doing this, we would transform a single big graph into multiple (possibly disconnected) sub-graphs, which was not a problem since the network has a global graph pooling layer in the end that fuses the sub-graphs information. This simple trick reduced 4 times the vRAM usage and sped up training by a factor of 5 in some cases.</p>
<h2>Deduplication</h2>
<p>Most of the configuration sets for layout contain a lot of duplication. However, the runtime for the duplicated configs can vary quite a bit and make training less stable. Thus, we opted for removing all the duplicated configs for layout.</p>
<h2>Compression</h2>
<p>Even with pruning and de-duplication, the RAM usage to load all configs to memory for NLP collection was super high. We circumvent that issue by compressing <code>node_config_feat</code> beforehand and only decompressing it on-the-fly in the dataloader after config sampling. This enabled us to load all data to memory at the beginning of training, which reduced IO/CPU bottlenecks considerably and allowed us to train faster.</p>
<p>The idea behind the compression is that each <code>node_config_feat</code> 6-dim vector (input, output and kernel) can only have 7 possible values (-1, 0, 1, 2, 3, 4, 5) and, thus, can be represented by a single integer in base-7 (from 0 to 7^6).</p>
<h2>Changing pad value in <code>node_feat</code></h2>
<p>We noted that the features in <code>node_feat</code> were 0 padded. Whilst this is not a problem for most features, for others like <code>layout_minor_to_major_*</code> this can be ambiguous since 0 is a valid axis index. Also, the <code>node_config_feat</code> are -1 padded, which makes it incompatible with <code>layout_minor_to_major_*</code> from <code>node_feat</code>. With that in mind, we re-generated <code>node_feat</code> with -1 padded and this allowed us to use a single embedding matrix for both <code>node_feat[134:]</code> and <code>node_config_feat</code>.</p>
<h1>Data preprocessing</h1>
<p>For layout, we split <code>node_feat</code> into <code>node_feat[:134]</code> and <code>node_feat[134:]</code> (<code>layout_minor_to_major_*</code>). The former was simply normalised using a <code>StandardScaler</code>, while the latter, along with <code>node_config_feat</code>, was fed into a learned embedding matrix (4 channels). We found that the normalisation is essential here since <code>node_feat</code> has features like <code>*_sum</code> and <code>*_product</code> that can be very high and, consequently, disrupt the optimisation.</p>
<p>For <code>node_opcode</code>, we also used a separate embedding layer with 16 channels. The input to the network is the concatenation of all features aforementioned and, for each graph, we sample on-the-fly 64 (default) or 128 (random) configs to form the input batch. For tile, on the other hand, we opt to use late fusion to integrate <code>config_feat</code> into the network.</p>
<h1>Network architecture</h1>
<p>Our network architecture was quite simple. We first feed the input features to a Linear block to map it to a 256d embedding vector followed by 2x Conv blocks, global graph mean pooling and a final linear layer.</p>
<p>As for the graph convolutional layer itself, we tried many types but none was better than <code>SAGEConv</code>. In particular, I had good experience with GAT variants in the past but none worked well in this competition. If I were to guess the reason, I'd say that in the other application the graph itself was quite noisy, so attention helped to "ignore" the connections that were not meaningful. However, for TPU graphs, all connections are "real" and important so graph attention was not that helpful. Nonetheless, we found two other types of attention that were useful: self-channel attention and cross-config attention.</p>
<h2>Self-Channel Attention</h2>
<p>We borrowed the idea from Squeeze-and-Excitation to create a channel-wise attention layer. We first apply a Linear layer to bottleneck the channel dimensions (8x reduction) followed by <code>ReLU</code>. Then, we applied a second linear layer to increase the channels again to the original value followed by sigmoid. We finish by applying element wise multiplication on the obtained feature map and the original input.</p>
<p>The idea behind this is to capture the correlations between channels and use it to suppress less useful ones while enhancing others. </p>
<h2>Cross-Config Attention</h2>
<p>Another dimension that we can exploit attention is the batch plane (cross-configs). We designed a very simple block that allows the model to explicitly "compare" each config against the others throughout the network. We found this to be much better than letting the model infer for each config individually and only compare them implicitly via the loss function (<code>PairwiseHingeLoss</code>). The attention code is as follows:</p>
<pre><code> (nn.Module):
():
().__init__()
.temperature = nn.Parameter(torch.tensor())
():
scores = (x / .temperature).softmax(dim=)
x = x * scores
x
</code></pre>
<p>By applying this simple layer after the self-channel attention at every block of the network, it gave us a huge boost for default collections. For inference, we simply use a reasonably large batch size of 128. However, since the prediction depends on the batch, we can leverage it further by applying TTA to generate <code>N</code> (10) permutations of the configs and average the result after sorting it back to the original order.</p>
<h2>Linear/Conv blocks design</h2>
<p>To create our Linear/Conv blocks we followed the good practices in computer vision. We start by using <code>InstanceNorm</code> to normalise the input feature map, followed by <code>Linear</code>/<code>SAGEConv</code> layer, <code>SelfChannelAttetion</code> and <code>CrossConfigAttetion</code> (we concat the output with its input to preserve the individuality of each sample). Then, we sum the residual connection and finish with <code>GELU</code> and dropout.</p>
<h1>Ensembling</h1>
<p>Our best single model prediction scored 0.714 (0.748) on private (public) LB. However, since the number of test samples is quite low for some collections, we opted to use ensembles to improve the results and prevent shaking up. Our best result was 0.736 (0.757) LB by using the simple average of 5-10 models for each collection but we sadly didn't select this sub.</p>
<h1>Things that didn't work</h1>
<ul>
<li>Train together on both random and default data</li>
<li>2nd level stacking on top of model's embeddings/predictions (worked well locally but not that well on LB)</li>
<li>Pseudo labelling test set</li>
<li>Finetunning models for specific graphs in test set (worked well locally but not that well on LB)</li>
<li>Different ways to sample the configs, e.g., annealing the runtime spacing between configs</li>
<li>Other loss functions</li>
<li>Gradient accumulation and training with more than one graph at a time</li>
</ul>
<h1>Sources</h1>
<ul>
<li>Our code can be found <a href="https://github.com/thanhhau097/google_fast_or_slow/tree/main" target="_blank">in this GitHub repo</a></li>
<li>Our work was based/forked on <a href="https://www.kaggle.com/werus23" target="_blank">@werus23</a> <a href="https://www.kaggle.com/code/werus23/tile-xla-end-to-end-train-infer" target="_blank">public kernel</a> (thank you!)</li>
<li>The modified layout dataset with -1 padding can be found <a href="https://www.kaggle.com/datasets/tomirol/layout-npz-padding" target="_blank">here</a></li>
</ul>
<p>I made a quick diagram of our network, it's a bit crap but should give a good idea 😅</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1648129%2F7cf79a021748ba6f4b38529447419992%2Fwriteup_graph_model.png?generation=1700408602690996&alt=media" alt=""></p>
<p>Thank you! I use a tool called <a href="https://app.diagrams.net/" target="_blank">drawIo</a></p>
<p>Thank you! For the ensemble, we train the same model architecture many (5 - 10 usually) times with different random seeds (main impact is in the model's weights initialisation). Then, we just load each model/trained weight individually to make the prediction and average them up</p>
<p>Sorry for the late response, was away recently. We used a RTX 4090 and it took around 1-2 hours (depends on the collection) to train the models after the optimisations we described in the thread.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 201st Place Solution for the Google - Fast or Slow? Predict AI Model Runtime | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>1. Introduction</h1>
<p>I am happy to be part of Google - Fast or Slow? Predict AI Model Runtime. I want to express my appreciation to the organizers, sponsors, and Kaggle staff for their efforts, and I hope everyone has the best time. This competition and other participants provided me with a lot of knowledge.</p>
<p>I am grateful to MIHU for providing the public notebook <a href="https://www.kaggle.com/code/chenboluo/simple-prediction-for-five-datasets?scriptVersionId=145767932" target="_blank">https://www.kaggle.com/code/chenboluo/simple-prediction-for-five-datasets?scriptVersionId=145767932</a></p>
<h1>2. Context</h1>
<ul>
<li>Business context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime</a></li>
<li>Data context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/data" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/data</a></li>
</ul>
<h1>3. Overview of the approach</h1>
<p>The solution was a copy of the public notebook(Public/Private LB of 0.39199/0.27376) <br>
with adding dataset created as output of public notebook (Public/Private LB of 0.39199/0.27376).</p>
<p>The data preprocessing process: Adjacency matrix. Virtual first node.</p>
<p>The algorithms employed: modified Bert.</p>
<ul>
<li>Inference: <br>
(copy codes given by MIHU in a public notebook <a href="url" target="_blank">https://www.kaggle.com/code/chenboluo/simple-prediction-for-five-datasets?scriptVersionId=145767932</a>)<br>
The validation strategy: split train and valid dataset.</li>
</ul>
<h1>4. Method modified Bert.</h1>
<p>Solution: </p>
<table>
<thead>
<tr>
<th>notebook</th>
<th>score private</th>
</tr>
</thead>
<tbody>
<tr>
<td>MIHU public <a href="https://www.kaggle.com/code/liudacheldieva/simple-prediction-for-five-datasets-2d0336?scriptVersionId=151176695" target="_blank">https://www.kaggle.com/code/liudacheldieva/simple-prediction-for-five-datasets-2d0336?scriptVersionId=151176695</a></td>
<td>0.27376</td>
</tr>
<tr>
<td>Change: add output of public notebook as input. Copy input to output.</td>
<td>0.27376</td>
</tr>
</tbody>
</table>
<p><br></p>
<h1>5. Final result</h1>
<table>
<thead>
<tr>
<th>public LB</th>
<th>private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>0.39199</strong></td>
<td>0.27376</td>
</tr>
<tr>
<td>0.13262</td>
<td>0.15293</td>
</tr>
<tr>
<td>0.12882</td>
<td>0.14862</td>
</tr>
<tr>
<td>0.14798</td>
<td>0.12904</td>
</tr>
<tr>
<td>0.14798</td>
<td>0.12904</td>
</tr>
<tr>
<td>0.15345</td>
<td>0.13017</td>
</tr>
</tbody>
</table>
<h1>6. Sources</h1>
<ul>
<li><a href="url" target="_blank">https://www.kaggle.com/code/chenboluo/simple-prediction-for-five-datasets?scriptVersionId=145767932</a></li>
<li><a href="url" target="_blank">https://www.kaggle.com/datasets/liudacheldieva/gf-sub-last</a></li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | 2nd Place Solution for the Google - Fast or Slow? Predict AI Model Runtime Competition | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>We express our gratitude to Kaggle as well as Google’s TPU team for organizing this remarkable challenge.</p>
<p>The code of the solution is available on <a href="https://github.com/Obs01ete/kaggle_latenciaga/tree/master" target="_blank">Github: Fast or Slow by Latenciaga</a>.</p>
<h2>Introduction</h2>
<p>Our implementation is a SageConv-based graph neural network (GNN) operating on whole graphs and trained in PyTorch/PyTorch-Geometric. The GNN was trained with the help of one or two losses, including a novel DiffMat loss, which we will discuss later.</p>
<h2>Dataset preprocessing</h2>
<p>We preprocess data from all 5 subsets by removing duplicates by config. We discovered that for each graph, several instances of configurations (all node-wise concatenated together for Layout and subgraph for Tile) are identical, while the corresponding runtimes are different with a 0.4% max-to-min difference. We reduce these groups by a minimum. For Layout-XLA, we filtered out all Unet graphs since we identified that <code>unet_3d.4x4.bf16</code> is badly corrupted. For the same reason, we removed <code>mlperf_bert_batch_24_2x2</code> from Layout-XLA-Default validation to improve the stability of the validation. We identified many other graphs whose data is seemingly corrupted, but we did not filter them out. As a part of preprocessing, we repack the NPZs for Layout so that for each graph, each config+runtime measurement (out of 100k or less) can be loaded from NPZ individually without loading the entire NPZ. With this repacking, thanks to lazy loading, random reads were accelerated 5-10 times, resulting in a similar reduction of training wall clock time, whereas the training became GPU-bound instead of data-loading bound.</p>
<h2>Model</h2>
<p>We train 5 models from scratch, one for each subset, applying different hyperparameters as summarized in the table below. All GNN layers are SageConv layers with residual connections whenever the number of input and output channels are the same.</p>
<table>
<thead>
<tr>
<th>subsets</th>
<th>layers x channels</th>
<th># parameters</th>
</tr>
</thead>
<tbody>
<tr>
<td>Layout-XLA</td>
<td>2x64 + 2x128 + 2x256</td>
<td>270k</td>
</tr>
<tr>
<td>Layout-NLP & Tile</td>
<td>4x256 + 4x512</td>
<td>2.3M</td>
</tr>
</tbody>
</table>
<p><br></p>
<p>The node types are embedded into 12 dimensions. Node features are compressed with <code>sign(x)*log(abs(x))</code> and shaped into 20 dimensions by a linear layer. For Layout, the configs are not transformed; for Tile, the graph configuration is broadcast to all nodes. We apply early fusion by combining the three above into a single feature vector before passing it to GNN layers. Features produced by the GNN layer stack are transformed to one value per node and then sum-reduced to form a single graph-wise prediction. </p>
<h2>Training procedure</h2>
<p>We follow training and validation splits provided by the competition authors. For all 5 subsets, the training was only performed on a training split.</p>
<p>The batch is organized into 2 levels of hierarchy: the upper level is different graphs, and the lower level is the same graph and different configurations, grouped in microbatches of the same size (also known as slates). This procedure allows applying ranking loss to the group of samples within a microbatch. We found that using some sort of ranking loss is essential for the score. Models trained with a ranking loss (ListMLE, MarginRankingLoss) heavily outperformed element-wise losses (MAPE, etc). </p>
<table>
<thead>
<tr>
<th>hyperparameter</th>
<th>Tile subset</th>
<th>Layout- XLA-Random</th>
<th>Layout- XLA-Default</th>
<th>Layout- NLP-Random</th>
<th>Layout- NLP-Default</th>
</tr>
</thead>
<tbody>
<tr>
<td>microbatch size</td>
<td>10</td>
<td>4</td>
<td>4</td>
<td>10</td>
<td>10</td>
</tr>
<tr>
<td>number of microbatches in a batch</td>
<td>100</td>
<td>10</td>
<td>10</td>
<td>4</td>
<td>4</td>
</tr>
<tr>
<td>batch size</td>
<td>1000</td>
<td>40</td>
<td>40</td>
<td>40</td>
<td>40</td>
</tr>
</tbody>
</table>
<p><br></p>
<p>The following hyperparameters were set:</p>
<ol>
<li>Adam/AdamW optimizer,</li>
<li>Learning rate 1e-3,</li>
<li>400k iterations,</li>
<li>Step learning rate scheduler at 240k, 280k, 320k, and 360k by factor of <code>1/sqrt(10)</code>.</li>
</ol>
<p>Training time is approximately 20 hours on A100 for each of 5 subsets. No early stopping was employed. All snapshots for submission were taken from the 400k-th iteration.</p>
<p>Losses used for training:</p>
<ol>
<li>ListMLE for Layout-NLP,</li>
<li>A novel DiffMat loss for Tile,</li>
<li>For Layout-XLA, it is a combination of 2 losses: the DiffMat loss and MAPE loss.</li>
</ol>
<p>For ListMLE loss, we used prediction norm-clipping to avoid numerical instability resulting from dividing a big number by a big number. We do not use prediction L2 normalization before ListMLE loss since we find it damages the score.</p>
<p>The novel DiffMat loss is described with the following algorithm. Within a microbatch, a full antisymmetric matrix of pairwise differences is constructed for the predictions and for the targets. The upper triangular matrix is taken from the difference matrix and flattened. Margin Ranking Loss with a margin of 0.01 is applied between predicted values and zeros. This novel loss, combined with MAPE loss, consistently outperformed ListMLE on XLA.</p>
<p><img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/191000e669012bb9d8cae52a309d73ac4d9a57a7/assets/diffmat.png" alt="difffmat"></p>
<h2>Remarks on the validation (CV) stability</h2>
<p>We found Kendall tau on the validation splits extremely unstable for XLA Random and Default since the dataset is relatively small, and there is a significant domain gap between train and validation, and presumably test. Repeats of training results in up to 13 percentage points of difference between outcomes. </p>
<h2>Experiments that did not work</h2>
<h3>Data filtration</h3>
<p>Some graphs’ data is badly damaged. For example, <code>magenta_dynamic</code> has the following rollout of runtimes vs config ID. In no way can these be measurements from the same graph. </p>
<p><img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/main/assets/damaged1.png" alt=""></p>
<p>Below are other examples where we are unsure about the conditions in which these measurements were performed.</p>
<p><img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/main/assets/damaged2.png" alt=""><br>
<img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/main/assets/damaged3.png" alt=""></p>
<p>Nevertheless, we do not filter out these graphs and others since we could not reliably observe the improvement from their removal due to the earlier mentioned instability of validation Kendall numbers.</p>
<h3>Data recovery</h3>
<p>We tried to find the damaged data and remove it in an automatic manner by computing block-wise entropy of the runtimes between adjacent blocks. While the detection seems to work visually, we observed a negative impact on the score and did not proceed with this feature.</p>
<p>Example 1:</p>
<p><img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/main/assets/entropy1.png" alt="link"></p>
<p>Example 2:</p>
<p><img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/main/assets/entropy2.png" alt="link"></p>
<p>Before and after entropy filtration:</p>
<p><img src="https://raw.githubusercontent.com/Obs01ete/latenciaga_materials/main/assets/entropy3.png" alt="link"></p>
<h3>Other experiments we tried that did NOT work:</h3>
<ol>
<li>GATv2Conv, GATv2 backbone, GINEConv,</li>
<li>Dropout,</li>
<li>Training on merged Random and Default - hurts both,</li>
<li>Adding reverse edges,</li>
<li>Online hard negative mining (OHEM) - did not help since train loss is nowhere near zero,</li>
<li>Train blindly on the merged train and valid (trainval),</li>
<li>Train 4 folds and merge by mean latency and by mean reciprocal rank (MRR),</li>
<li>Periodic LR schedule.</li>
</ol>
<h2>Conclusion</h2>
<p>We found Google Fast or Slow to be a great competition, and we enjoyed it a lot, along with learning many new things, especially ranking losses.</p>
<p>Partially inspired by this competition, Dmitrii published an article <a href="https://pub.towardsai.net/ten-patterns-and-antipatterns-of-deep-learning-experimentation-e91bb0f6feda" target="_blank">Ten Patterns and Antipatterns of Deep Learning Experimentation</a> at Towards AI.</p>
<p>Thanks!</p>
<blockquote>
<p>One hypothesis could be that a small set of config changes affected the runtime a lot, while most of the config changes doesn't.</p>
</blockquote>
<p>The point is that, at least for the random search, the distribution of runtimes must be stationary across sample IDs. The distribution is indeed visually stationary for 95% of graphs, the more surprising it was to see non-stationary distributions, which may point to a bug in data collection. Indeed, as you noticed, the distribution may be sophisticated, multimodal, but, in my opinion, it should not be non-stationary for random sampling. It can be non-stationary for genetic algorithms (default sets), but the evolution of the distribution must be smooth, not abrupt, as in the examples in the post.</p>
<p>The code of our solution is available on <a href="https://github.com/Obs01ete/kaggle_latenciaga/tree/master" target="_blank">Github: Fast or Slow by Latenciaga</a>.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 33rd Solution Writeup and Discussion on GST | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, thanks Kaggle and the competition host for hosting this exiting competition and congrats to all the winners. I would like to share my solution (though not that good) mainly from the perspective of <a href="https://github.com/kaidic/GST" target="_blank"><strong>G</strong>raph <strong>S</strong>egment <strong>T</strong>raining (<strong>GST</strong>)</a>. The code is released <a href="https://github.com/JiangJiaWei1103/Google-Fast-or-Slow" target="_blank">here</a>.</p>
<h2>Overview</h2>
<ul>
<li>Data cleaning and preprocessing<ul>
<li>Add new features following instructions <a href="https://github.com/google-research-datasets/tpu_graphs/tree/main#graph-feature-extraction" target="_blank">here</a>.</li>
<li>Drop constant and quasi-constant features.</li>
<li>Label encode features related to <code>shape_element_type_is_X</code>.</li>
<li>Log transform features with max value greater than 20.</li></ul></li>
<li>Model architecture<ul>
<li>Train all models in the <strong>early-join</strong> manner (<em>i.e.,</em> fuse node and config features before getting the whole graph context).</li>
<li>Use <code>SAGEConv</code> as the GNN block.</li></ul></li>
<li>Training strategy<ul>
<li>Use <strong>GST</strong> (with history embedding table and stale embedding dropout) to train <em>layout</em> models in a collection-specific manner (<em>i.e.,</em> one model per collection).</li>
<li>Sample a subset of configurations to train models per iteration.</li></ul></li>
<li>Experimental Setup<ul>
<li>Loss criterion: <code>PairWiseHingeLoss</code> for <em>layout</em> and <code>ListMLE</code> for <em>tile</em></li>
<li>Optimizer: <code>AdamW</code> with base learning rate <code>1e-3</code> (I decrease lr when increasing #epochs)</li>
<li>Learning rate scheduler: Cosine schedule without warmup</li>
<li>Checkpoint: Always pick the model at the last epoch</li></ul></li>
</ul>
<h2>Data Cleaning and Preprocessing</h2>
<p>I process the data by a simple four-stage workflow. Firstly, I find out that some of the features are constant among all the datasets, which can be viewed as the redundant dimensions and dropped directly. Also, those with constant ratio like above 0.999 (<em>i.e.,</em> quasi-constant) are thrown away. Then, I label encode the remaining dimensions related to <code>shape_element_type_is_X</code>, which can be represented with a dense embedding. Finally, considering features can span a wide value range (also, some outliers exist), I simply use <code>np.log1p</code> to log transform features with max value greater than 20.<br>
After processing, the node feature dimension drops to 116 and 50 (89 and 33 without new features added) for <em>xla</em> and <em>nlp</em>, respectively.</p>
<h2>CV Scheme</h2>
<p>Considering there are only ~4 graphs and 8 graphs for <em>xla</em> and <em>nlp</em> evaluated on public LB, I try to enlarge the validation set by splitting train+val stratified on runtime, which can somewhat balance the intrinsic graph properties (I explore relationship between graph stats and runtime in <a href="https://www.kaggle.com/code/abaojiang/google-fast-or-slow-detailed-eda" target="_blank">this notebook</a>). However, I don't think it's much different from just using the official train-val splitting.</p>
<h2>Model Architecture</h2>
<p><a href="https://postimg.cc/mtC0KZzX" target="_blank"><img src="https://i.postimg.cc/dtxwkLqY/Screenshot-2023-11-20-at-15-10-31.png" alt="Screenshot-2023-11-20-at-15-10-31.png"></a><br>
The figure above illustrates the overview of model architecture, where \(d_n \) and \(d_c \) denote the node and config feature dimensions. And, \(L \) is the number of graph convolution layers.<br>
Since my first submission on 22nd, Oct, I use early-join to fuse the node and config features. After experimenting with different GNN blocks (<em>e.g.,</em> <code>GATConv</code>, <code>GATv2Conv</code>, <code>GINConv</code>), <code>SAGEConv</code> always outperforms, so I stick to it till the end. Also \(L \) is always set to 3. To be honest, there's no fancy design in my model architecture. Hence, I want to talk more about the training strategy.</p>
<h2>Training Strategy - <strong>G</strong>raph <strong>S</strong>egment <strong>T</strong>raining (GST)</h2>
<p>Considering the memory limitation, I quickly decide to choose off-the-shelf <strong>GST</strong> as my training framework. As there exists some unsolved issues in the official implementation of <strong>GST</strong>, I rewrite the pipeline without <a href="https://github.com/rampasek/GraphGPS" target="_blank">GraphGPS</a>.<br>
The main concern with <strong>GST</strong> is that the training loss increases as the training process progresses, but validation performance still improves over time. After fixing the \(\eta \), the weight for each graph segment, for final sum pooling, the training loss decreases normally as shown below (special thanks to <a href="https://www.kaggle.com/dsfhe49854" target="_blank">@dsfhe49854</a> 's analysis <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/discussion/448367#2497447" target="_blank">here</a>),<br>
<a href="https://postimg.cc/jCyB81QT" target="_blank"><img src="https://i.postimg.cc/Vsh1NQJJ/Screenshot-2023-11-20-at-17-50-00-Weights-Biases.png" alt="Screenshot-2023-11-20-at-17-50-00-Weights-Biases.png"></a><br>
Let's see how \(\eta \) is derived in the original paper. Let \(n \) be the number of segments for one graph and \(k \) be the number of segments to be trained per iteration. Also, select \(p \) as the dropout ratio of <strong>stale embedding dropout</strong>. Assume we sample only one segment for training per iteration(<em>i.e.,</em> \(k = 1\)), as described in the paper. The weight \(\alpha \) of the trained segment can be derived as follows, <br>
$$<br>
(n-k)p + k\alpha = n<br>
$$<br>
$$<br>
\alpha = (1-p)\frac{n}{k} + p<br>
$$</p>
<p>The logic behind the scene is that the final runtime estimation is the <strong>sum pooling</strong> of runtimes of all segments. Considering some segments are dropped with probability \(p \), we need to increase the weight of the trained segment for compensation. However, the problem is that most of the entries in historical embedding table are zeros. Therefore, in early epochs, the objective can be approximated as,<br>
$$<br>
\hat{y} = \alpha \hat{y}_{i} ,<br>
$$</p>
<p>where \(\hat{y} \) is the predicting runtime of the current graph and \(\hat{y}_{i} \) is the predicting runtime of the segment \(i \) of the current graph. What's interesting is that I observe the <strong>unfixed \(\eta \)</strong> always leads to better generalizability compared with the fixed one. Also, if the model is trained with sufficient number of iterations, the training loss actually goes downward (the red line turns the direction at ~100 epochs).</p>
<h2>Experimental Results</h2>
<p>Following table shows the local CV scores of my final submission.</p>
<table>
<thead>
<tr>
<th>Collection</th>
<th>CV</th>
</tr>
</thead>
<tbody>
<tr>
<td><em>tile</em></td>
<td>0.9551</td>
</tr>
<tr>
<td><em>xla-default</em></td>
<td>0.3188</td>
</tr>
<tr>
<td><em>xla-random</em></td>
<td>0.5569</td>
</tr>
<tr>
<td><em>nlp-default</em></td>
<td>0.5053</td>
</tr>
<tr>
<td><em>nlp-random</em></td>
<td>0.8845</td>
</tr>
</tbody>
</table>
<h2>What Didn't Work for Me</h2>
<ul>
<li>Use other GNN blocks (<em>e.g.,</em> <code>GATConv</code>, <code>GATv2Conv</code>, <code>GINConv</code>)</li>
<li>Retrain models on the whole dataset</li>
<li>Finetune <em>default</em> using the pretrained weights from <em>random</em><ul>
<li>Freezing different parts of network makes no difference.</li></ul></li>
<li>Segment graphs with other strategies (<em>e.g.,</em> Metis)</li>
</ul>
<h2>Conclusion</h2>
<p>It's not good to stick to only one method (<strong>GST</strong>) for all implementation, I should have explored other potential solutions like all amazing writeups I've digested so far. Though the result isn't that promising this time, I will keep progressing and learning from the top-tiers. This journey never stops! Thanks for your patience!</p> |
Google - Fast or Slow? Predict AI Model Runtime | 3rd place solution write-up | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, thanks for hosting this competition. It was my first Kaggle competition which I entered on a whim because I had some free time. It turned out to be a lot of funstration (fun + frustration). Looking at all the amazing solutions from the other teams, I consider myself incredibly lucky to have ranked this high!</p>
<p><strong>Edit:</strong> After cleaning up the code I noticed that I forgot to mention some things which I now added. The code is now available <a href="https://github.com/jafluri/kaggle_tpu_graph" target="_blank">here</a>.</p>
<h2>Overview</h2>
<p>My solution is more or less composed of three parts. Minor feature extraction and engineering, tinkering with the graph, e.g. pruning, and training a graph neural network (GNN). The GNN layers are based on the <a href="https://openreview.net/pdf?id=lMMaNf6oxKM" target="_blank">GPS layers</a>, using SAGE convolutions, <a href="https://arxiv.org/pdf/2006.04768.pdf" target="_blank">Linformers</a> and <a href="https://arxiv.org/pdf/2110.07875.pdf" target="_blank">learnable positional encodings</a>. Note that this discussion concerns mainly the layout dataset. The solution for the tile dataset is mentioned briefly at the end.</p>
<h2>Input Features</h2>
<p>I used all 140 provided input features and used a simple log transform after shifting them such that each feature was at least 1. Additionally, I went through the protocol buffers and extracted the following features:</p>
<ul>
<li><code>has_dynamic_com</code>: A flag indicating whether the graph has dynamic computations.</li>
<li><code>is_root_of_com</code>: A flag indicating if a node is the output node of a computation.</li>
<li><code>indices_are_sorted</code>: A flag that I am not sure why I added it.</li>
<li>For the <code>dot</code> operation, I extracted <code>lhs_contracting_dimensions</code>, <code>rhs_contracting_dimensions</code>, <br>
<code>lhs_batch_dimensions</code> and <code>rhs_batch_dimensions</code>, which are all integer sequences that I padded to a length of 3, so 12 features in total.</li>
<li>For the <code>gather</code> operation I added the integer sequences <code>offset_dims</code>, <code>collapsed_slice_dims</code> and <br>
<code>start_index_map</code> padded to length 3, the single integer <code>index_vector_dim</code> and the sequence <code>gather_slice_sizes</code> padded to length 5.</li>
</ul>
<p>The padding lengths were chosen based on the longest sequences contained in the dataset and I always used -1 as the padding value. Some of these features were useless depending on the applied graph pruning, but I left them in the input anyway. Additionally, while going through the protobufs, I added the input shapes (6D) of the two input arguments for the <code>dot</code> and <code>conv</code> operations as additional features, making sure that they are always ordered in the same way (e.g. lhs, rhs arguments for the <code>dot</code>). This adds 16 dimensions to the input (with sum and products of the shapes). I did this because I thought that it might be difficult for the network to learn the order of the inputs and dimensions which are reduced in these operations given solely the message-passing networks.<br>
I also took the 30 dimensional features and added them to the input features once modulus 128 (<code>(x % 128)/128</code> and once as true divide <code>(x // 128)/10</code> with some normalization. I did this to make it easier for the network to process the dimensions of the tensors and compare them to the <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/discussion/437673" target="_blank">register size</a> of the TPUs.</p>
<h2>OP code embeddings and positional encoding</h2>
<p>I used 128-dimensional embeddings for the OP codes. For the positional encodings, I used RWPE described <a href="https://arxiv.org/pdf/2110.07875.pdf" target="_blank">here</a>. I created 16 dimensional PEs with the directed adjacency matrix and 112 using the undirected one, for a total of 128 features. The encoding was always calculated with the full graph, independent of the pruning that was used during the training of the network.</p>
<h2>Graph Modifications</h2>
<p>I experimented with three versions of pruning/pooling:</p>
<ul>
<li>Dropping all nodes and connections besides the configurable one. This results essentially in training an MLP.</li>
<li>Dropping all the nodes besides the configurable nodes and their inputs/outputs.</li>
<li>Merging all nodes besides the configurable nodes and their inputs/outputs. Two nodes were merged if they had at least one connection and were neither configurable nor an input or output of a configurable node. This was done until no further merging was possible. The merged nodes had a unique OP code but their features are set to zero. </li>
</ul>
<p>Addionally, I added a virtual output node, connecting all nodes that produce ouputs.</p>
<h2>GNN</h2>
<p>The GNN consists of SAGEConvolutions and Linformer. The architecture is shown in the figure below. The SAGEConvolutions use both the input and the output nodes with different weights and a message dimension of half the size of the input dimension. The Linformer dimension was set to 128 (or 256 in some experiments). I used Sigmoid Linear Units (SiLU) activation functions and a lot of layer normalisation.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F10842317%2F8203b36d4bbe981f7d172cd270451c94%2Flayer.drawio.png?generation=1700420261387549&alt=media" alt=""></p>
<p>The training was done with Adam and a cosine annealing scheduler. I tried batch sizes of 8, 16 and 32 with 5, 8 or 10 configs and pairwise hinge-loss. I trained on all collections at the same time and then did finetuning on the individual collections. However, I did not have time to train a network on all collections with the merged nodes. I only implemented this towards the very end and trained only one network on the <code>xla:default</code> collection, which gave me the best CV. The final submission was composed of networks trained with my second pruning strategy for <code>xla:random</code> and the <code>nlp</code> collections and the third pruning strategy for <code>xla:default</code>.</p>
<h1>Tile Network</h1>
<p>The tile network was a simple GNN with 5 SAGEConvolutions, no extra features and no positional encodings. </p>
<h2>Other stuff</h2>
<p>These are things I tried out but failed or could not evaluate if they had a consistent positive impact on the results. </p>
<ul>
<li>Node dropout and test-time augmentations with the dropout. </li>
<li>Using the full graph</li>
<li>Transformers instead of Linformers (Memory)</li>
<li>Some self-implemented attention with configs and features</li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | 4th simple mlp solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>`class SimpleMLP(torch.nn.Module):</p>
<pre><code>def (self):
().()
self.embedding = torch.nn.(,)
self.config_dense = torch.nn.(nn.(+, ),
nn.(),
nn.(, ),
nn.(),
)
self.node_dense = torch.nn.(nn.(*+, ),
nn.(),
nn.(, ),
nn.(),
)
self.output=torch.nn.(nn.(*+, ),
nn.(),
nn.(, ),
)
def (self,x_cfg,x_feat,x_op):
x_feat=x_feat.()
x_op=x_op.()
x_op = self.(x_op).(-,)
x_feat = torch.([x_feat,x_op],dim =)
x_feat = self.(x_feat)
x_graph = x_feat.()
x_graph = x_graph.((x_cfg),dim=)
x_cfg = torch.([x_cfg,x_graph],axis=)
x_cfg = self.(x_cfg)
x=(x_feat.T@x_cfg).((x_cfg),-)
x_cfg_mean=x_cfg.(dim=)
x = torch.([x,x_cfg_mean],axis=)
x=self.(x)
x=torch.(x)
return x
</code></pre>
<p>def load_data(row):</p>
<pre><code>node_feat_index=[,,,,,
,,,,
,,,
]
config_index=[,,,,,,,]
data= dict(np.load(row.path))
=data[][:,node_feat_index]
node_feat=pd.(,columns=[
node_feat[]=range(len(node_feat))
node_feat_link=node_feat.copy()
node_feat_link.columns=[i+ for i in node_feat_link.columns]
node_config_ids=pd.({:data[],:range(len(data[]))})
node_opcode=pd.({:range(len(data[])),:data[]})
edge_index=pd.(data[],columns=[,])
edge_index=edge_index[edge_index.id.isin(data[])]
edge_index=edge_index.merge(node_opcode,on=,how=).merge(node_opcode.rename(columns={:,:}),on=,how=)
edge_index=edge_index.merge(node_config_ids,on=,how=)
edge_index=edge_index.merge(node_feat,on=,how=).merge(node_feat_link,on=,how=)
all_features=[i for i in edge_index.columns if i not in [, , ,, ]]
node_feat_array=edge_index[all_features].values.astype(np.float32)
node_config_feat=data[][:,:,config_index]
node_opcode_array=edge_index[[,]].values
node_config_feat=node_config_feat[:,edge_index[].values,:]
label=data[].argsort().argsort()/len(data[])
return {:node_feat_array, #x_feat
:node_config_feat, #x_cfg
:node_opcode_array, #x_op
:label,
:data[],
:np.array(range(len(label)))
}</code></pre> |
Google - Fast or Slow? Predict AI Model Runtime | 53th place solution: Fast or Slow with Data Prunning and Pretraining | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Dataset preprocessing</h1>
<p>We have merged parts of the layout dataset for pretraining purposes:</p>
<ul>
<li>NLP = NLP.RANDOM + NLP.DEFAULT -> Pretrain data for NLP models</li>
<li>XLA = XLA.RANDOM + XLA.DEFAULT -> Pretrain data for XLA models</li>
</ul>
<p>Pretrained and finetuned models use fixed mean/std values which are calculated as average values of ‘random’ and ‘default’ datasets.</p>
<p>Unuseful (zero) data was deleted from the dataset for training speed up:</p>
<ul>
<li>Truncated features in LAYOUT.NLP dataset: nodes 140 -> 40, edges 18 -> 8 </li>
<li>Truncated features in LAYOUT.XLA dataset: nodes 140 -> 112, edges 18 -> 14</li>
</ul>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F554956%2F7bc2b9470906e2c8d343fdd71b26f9de%2Fdata_stat.png?generation=1701075640215878&alt=media" alt=""></p>
<h1>Training</h1>
<h2>LAYOUT dataset (<a href="https://github.com/belgraviton/gst_tpu/tree/main/scripts" target="_blank">github</a>):</h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F554956%2Fea563e44aec6ecbd67c573a0a352f8e6%2Fglob_pool.png?generation=1701075656696317&alt=media" alt=""></p>
<p>Solution:</p>
<ul>
<li>pretraining on full NLP and XLA datasets and finetune on specific ones</li>
<li>number of configs 64</li>
<li>loss margin strategy: 0.01 -> 0.1 -> 0.5</li>
<li>clip gradients for XLA:RANDOM</li>
<li>dropout 0.0</li>
<li>global pooling improvement with concatenate operation</li>
<li>hidden dim = 256</li>
<li>1 k epochs</li>
<li>CosineLRScheduler</li>
<li>Adam, lr = 1e-4</li>
</ul>
<p>Results: Kendall tau: NLP.DEFAULT 48.3%, NLP.RANDOM 85.2%, XLA.DEFAULT 29.6%, XLA.RANDOM 37.3%</p>
<h2>TILE dataset (<a href="https://github.com/belgraviton/tpupredict/blob/main/scripts/t03_99_MSEtl_10k.sh" target="_blank">github</a>):</h2>
<p>Solution:</p>
<ul>
<li>batchsize 16</li>
<li>number of configs 512</li>
<li>2 k epochs with early stop 200 epochs</li>
<li>Adam, lr = 1e-3</li>
</ul>
<p>Results: validation OPA: 90.82%</p>
<h2>Other experiments that did NOT work:</h2>
<p>GENConv+Transformer hybrid model from GraphGPS repo</p>
<p>Architecture design:</p>
<ul>
<li>number of layers</li>
<li>hidden dimension</li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | 58th place basic vanilla keras solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>The generated features are provided in the attached .txt file (note: it has manual inputs)<br>
Solution- <a href="https://www.kaggle.com/code/anshuman8514/58th-place-vanilla-keras-solution" target="_blank">https://www.kaggle.com/code/anshuman8514/58th-place-vanilla-keras-solution</a></p> |
Google - Fast or Slow? Predict AI Model Runtime | 5th Place Solution: GNN with Invariant Dimension Features | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks, and congratulations on your 1st place!</p>
<p>Update: Due to limited time, I could only train the final best model for 1.2 epochs out of 2 epochs. After the training of whole epochs finished, this single model achieved 1st place score…😢😢😢</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F9088007%2F07b81bbe731009d97fee08622f9997ba%2FF_TAVI6bcAAMHBg.jpeg?generation=1700401008267090&alt=media" alt=""></p>
<p>Thanks! Yeah, I'm going to publish the code later.</p>
<p>Thanks!<br>
I mean I concatenated the outputs of two independent graph convolutions. The pseudocode is like this:</p>
<pre><code>self.gconv = SAGEConv(mid_ch, mid_ch // , ...)
self.rev_gconv =SAGEConv(mid_ch, mid_ch // , ...)
rev_edge_index = torch.flip(edge_index, (,))
x = torch.cat([self.gconv(x, edge_index), self.rev_gconv(x, rev_edge_index)], dim=-))
</code></pre>
<p>Intuition: If we have an edge (u, v), we want to propagate information not only from u to v but also from v to u. However, the weight should not be equal because it's a directed edge.</p>
<p>I published a source code!<br>
<a href="https://github.com/knshnb/kaggle-tpu-graph-5th-place" target="_blank">https://github.com/knshnb/kaggle-tpu-graph-5th-place</a></p>
<p>Sorry, 43 was a mistake and it was 30 correctly (I was tired from the hard work…). I extracted 10 that end with <code>_{i}</code> from the node features, 14 dim numbers from the node features, 3 from the tile config, and 3 from the layout config.</p>
<p>Thanks for hosting the interesting competition, and congratulations to the winners!</p>
<h2>Overview</h2>
<p>My solution is based on an end-to-end graph neural network (GNN). I implemented a 3-layer GraphSage based on <a href="https://pytorch-geometric.readthedocs.io/en/latest/" target="_blank">PyG</a>. In each layer, I operate graph convolution in both directions of edges by different weights and concatenate the outputs.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F9088007%2Fa038962047b9285a904e29d787b3d1ff%2FTPUGraphs-GNN.drawio.png?generation=1702755579495636&alt=media" alt=""><br>
I trained the model to minimize pairwise hinge loss using the AdamW optimizer using a cosine annealing scheduler.<br>
For the loss, I used the average of a pairwise hinge loss among different configurations of the same graph and a pairwise hinge loss among all the samples in a batch (including different graphs). For this reason, I didn't use a subgraph but a whole graph as an input to GNN.</p>
<h2>Dimension Feature Embed by Transformer</h2>
<p>Node features include 30 features (including tile and layout configurations) for each of the 6 dimensions. A naive approach to input this to GNN is to simply flatten them (I call this naive model), but I considered the following two disadvantages.</p>
<ul>
<li>It drops prior information about feature correspondence across dimensions</li>
<li>The output should be invariant to the indexing order of dimensions (I'm not sure if this is exactly correct)</li>
</ul>
<p>To tackle these issues, I implemented a dimension feature embedding layer using a transformer that handles each dimension as a token. In this layer, I transform (6, 30) input to (6, mid_ch) by a transformer and reduce to (mid_ch) by taking the sum in the token dimension.<br>
Since most dimension features are exactly the same (padded ones), I could compute this efficiently by calculating embedding for only unique ones in each batch and copying them.</p>
<h2>Tile Config Dataset</h2>
<p>I trained the model using only the tile dataset.<br>
Using the transformer model, I could easily achieve 0.2 (nearly perfect) in public and private LB. The transformer model was significantly better than the naive approach on the validation Kendall tau score.</p>
<h2>Layout Config Dataset</h2>
<p>I trained the model using the whole layout dataset (random and default of xla and nlp). Also, including the tile dataset enhanced the performance a little.</p>
<p>I could not outperform the naive model by the transformer model in the validation score (due to limited time), but it was comparable. My final submission was an ensemble of naive models and transformer models.</p>
<h2>Tips</h2>
<ul>
<li>use the same opcode embedding for unary operations such as abs, ceil, cosine, etc.</li>
<li>override layout_minor_to_major by layout config features for configurable nodes</li>
<li><a href="https://arxiv.org/abs/1907.10903" target="_blank">DropEdge</a></li>
<li>apply log transformation to input features</li>
<li>oversampling</li>
<li>load layout config data by numpy's mmap mode to save RAM</li>
</ul>
<h2>What Didn't Work</h2>
<ul>
<li>graph pooling</li>
<li>pretrain on the tile dataset and finetune on the layout dataset</li>
<li>graph normalization</li>
<li>dropout node</li>
<li>GAT, GATv2, GIN</li>
<li>fp16</li>
<li>pseudo label</li>
</ul>
<h2>Acknowledgement</h2>
<p>I acknowledge Preferred Networks, Inc. for allowing me to use computational resources.</p>
<p>Source Code: <a href="https://github.com/knshnb/kaggle-tpu-graph-5th-place" target="_blank">https://github.com/knshnb/kaggle-tpu-graph-5th-place</a></p>
<p>Thanks for the comment. I learned a lot from your presentation!</p>
<p>I just focused on improving the validation score and did not care about public and private during the competition. According to the LB probing analysis by <a href="https://www.kaggle.com/charmq" target="_blank">@charmq</a>, it seems public data has some graphs that are far from training graphs, which caused high randomness.<br>
<a href="https://twitter.com/charmq00/status/1725675672222503043" target="_blank">https://twitter.com/charmq00/status/1725675672222503043</a><br>
(Sorry, the above tweet is in Japanese…)</p>
<p>For others, this is the post submission results I mentioned in the winner call.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F9088007%2F7da5830169c4933ab603971a32033ca4%2FScreen%20Shot%202023-12-11%20at%200.22.31.png?generation=1702222223063708&alt=media" alt=""></p> |
Google - Fast or Slow? Predict AI Model Runtime | 6th solution: Node-level Instance Norm + Residual SageConv on 5-hop-neighbour Subgraph | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1><strong>Training and inference code can be downloaded from:</strong></h1>
<p><a href="https://github.com/hengck23/solution-predict-ai-model-runtime/" target="_blank">https://github.com/hengck23/solution-predict-ai-model-runtime/</a> <br>
</p>
<h2>1. Layout runtime prediction</h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2Fb5c1c8af2f166b73061177ae313a2c6b%2FSelection_999(4192).png?generation=1701482437470415&alt=media" alt=""></p>
<p>main problem:</p>
<ul>
<li>we have very large graph as input. how to design learning model and algorithm that can fit into gpu memory? </li>
</ul>
<p>summary of approach :</p>
<ul>
<li>instead of using the whole graph, we can reduce it by considering only the 5-hop neighbours from node marked as "config id". We call this 5-hop-neighbour subgraph. We think this is reasonable becuase since we are comparing relative ranking of 2 graphs, and we just need to input the "difference nodes" (instead of the whole graph) to the neural net.</li>
</ul>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2F5e4c66d69dcf5ea590ad619c37dc2179%2FSelection_999(4193).png?generation=1701483096930612&alt=media" alt=""></p>
<ul>
<li>using the reduced subgraph, i can sample 32 to 100 configurations using all full subgraphs with a single 48-GB GPU card at training.</li>
<li>batch size is not an issue here, bcuase i am using gradient accumulation. We accumuluate over one subgraph at a time when training a batch.</li>
</ul>
<pre><code>optimizer.zero_grad()
for in range( r =
loss = net(r)
</code></pre>
<ul>
<li><p>normalisation is important. We use "graph instance norm" (over node), see paper[1], which works well with gradient accumulation </p></li>
<li><p>we use pairwise ranking loss in training loss.</p></li>
<li><p>We try 2 GNN: </p>
<ul>
<li>4-layer SAGE-conv[2] with residual shortcut</li>
<li>4-layer GIN-conv[3] </li></ul></li>
</ul>
<p>SAGE-conv is better than GIN-conv.</p>
<h2>2. Tile runtime prediction</h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2Fc13d2c462b0958161cd4ce09e4249bc7%2FSelection_999(4191).png?generation=1701482450756660&alt=media" alt=""></p>
<p>main problem:</p>
<ul>
<li>There is no issues here as the graph in the kaggle training data are much smaller. These are actually subgraphs of the much larger original computation graph.</li>
</ul>
<p>summary of approach</p>
<ul>
<li>We still use "graph instance norm" (over node) [1], and smae gradient accumulation apporach, with batch size =64.</li>
<li>We try both SAGE-conv[2] and GAT-conv[4]. GAT-conv gives better results.</li>
<li>Since we are interested in top 5 ranks, we find listMLE is a better loss.</li>
</ul>
<hr>
<h2>[Reference]</h2>
<p>[1] GraphNorm: A Principled Approach to Accelerating Graph Neural Network Training<br>
<a href="https://arxiv.org/abs/2009.03294" target="_blank">https://arxiv.org/abs/2009.03294</a> <br>
[2] Inductive Representation Learning on Large Graphs<br>
<a href="https://arxiv.org/abs/1706.02216" target="_blank">https://arxiv.org/abs/1706.02216</a> <br>
[3] How Powerful are Graph Neural Networks?<br>
<a href="https://arxiv.org/pdf/1810.00826.pdf" target="_blank">https://arxiv.org/pdf/1810.00826.pdf</a><br>
[4] Graph Attention Networks <br>
<a href="https://arxiv.org/abs/1710.10903" target="_blank">https://arxiv.org/abs/1710.10903</a></p>
<hr>
<h2>local validation and public/private score</h2>
<p>The metric are: slowndown (top-5) for tile and kendall tau for layout.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2F0caab07b1cf25d81b358b1234d459b8c%2FSelection_999(4194).png?generation=1701488206301120&alt=media" alt=""></p>
<hr>
<h2>Acknowledgment</h2>
<h2><em>"I would like to express my sincere gratitude to HP for the generous provision of the Z8-G4 Data Science Workstation that was instrumental in the successful completion of kaggle competition. The two 48GB Nvidia Quadro RTX 8000 GPU cards give me a distinct advantage to easily bulid models with the largest public graph dataset TPUGraphs, with 100 millions graphs of 10 thousands nodes."</em></h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2F1ec4d755accef83d3fd01659f985e67e%2FSelection_999(3942).png?generation=1700269712680505&alt=media" alt=""></p>
<p>it seems that the trick to winning is to select the correct submission<br>
(i.e. one should not only look at the average metric of the validation data, but the metric of each validation graph) </p> |
Google - Fast or Slow? Predict AI Model Runtime | 7th Place Solution Write-up | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks for hosting this fascinating competition, and congratulations to the winners! I really learned a lot through this competition.</p>
<p><strong>Tile Part:</strong><br>
My approach to the Tile part was quite similar to the official code. I also check the public tile codes and find the validation score was already quite high , and ensembling them didn't lead to significant improvements, so I didn't invest too much time in this section.</p>
<p><strong>Layout Part:</strong><br>
For the Layout part, I primarily referred to the gst code <a href="url" target="_blank">https://github.com/kaidic/GST</a>. However, I encountered some challenges in making it work efficiently due to GPU memory constraints. Eventually, I used a sampling method to reduce GPU usage. </p>
<p><strong>Sampling Method:</strong><br>
The raw data consumed too much memory, so I decided to sample only 500 or 1000 configurations for each sample. This significantly reduced training time and GPU memory requirements.</p>
<p><strong>Training Strategy:</strong></p>
<ol>
<li>Training them all.</li>
<li>Training seperately based on the edge & node shapes. While the test data didn't explicitly specify the model type, we could infer it based on the edge & node shapes.</li>
<li>Using different kinds of parameters, such as graph conv type, learning rate, batchsize, layers number and hidden size. </li>
</ol>
<p><strong>Ensembling</strong><br>
Ensembling above models proved to be effective in improving the results. Every time I trained a new model, I found that ensembling it with existing models contributed to score improvements.</p>
<p><strong>Regarding the Public Score:</strong><br>
I did identify the fact mentioned in a post <a href="url" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/discussion/456083</a> but couldn't fully understand why it worked. I exercised extreme caution in utilizing it during the private phase since I considered it very risky.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 84th Solution: Based on Transformer, the GraphTPU model | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>In this task, we enhanced the accuracy of the model by replacing the MLP layout in the open-source code Google GraphTPU with a Transformer. Additionally, we employed preprocessing techniques that effectively contributed to the successful completion of the task.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 8th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to competition organizer giving us such a interseting competition.Our team joined very late we don't have time to deepdive but we found a simple solution very useful.</p>
<h1>Data Processing & Feature Engineering</h1>
<p>Tile: count of config&node&edge, mean,max,std,last of node_feat, mean,max,std of config_feat<br>
Layout: flatten node_config_feat -> remove unique value columns -> remove duplicate columns</p>
<h1>Train Data</h1>
<p>The keypoint of our layout solution is finding the most similar train data for each test data. We can observe some data have almost same edge&node number and can guess they are same model type except size,the test data should be the same model with different batch size.<br>
e.g.</p>
<pre><code>train: small_bert_bert_en_uncased_L-12_H-768_A-12_batch_size_16_test
valid: small_bert_bert_en_uncased_L-12_H-768_A-12_batch_size_32_test
test(same edge&node number) should be the small_bert_bert_en_uncased_L-12_H-768_A-12_batch_size_64_test
</code></pre>
<p>We cannot find all the similar train data for each test data, but enough to get a good result.And it's very fast for iteration.</p>
<h1>Model</h1>
<p>transform the target to minmaxscaler , use xentropy as the loss function, lightgbm as model, we don't use validation just give a fix round for each model.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 97th place solution for Google - Fast or Slow? Predict AI Model Runtime | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to Kaggle and Google for hosting this great competition. I learned a lot about training graph data models, especially how to deal with memory efficiency and optimize performance. </p>
<p>I started by training a modified BERT model by <a href="https://www.kaggle.com/KSMCG90" target="_blank">@KSMCG90</a> using cross-validation and the <a href="https://lightning.ai/" target="_blank">Lightning AI</a> library. But this model was too demanding on memory for the layout dataset. So, I switched to the GNN (Graph Neural Network) model by <a href="https://www.kaggle.com/GUSTHEMA" target="_blank">@GUSTHEMA</a> for the layout task. Since the tile and layout datasets didn't show any significant correlation, I built two separate models: one BERT model for the tile dataset and one GNN model for the layout dataset. </p>
<p>The solution <a href="https://www.kaggle.com/code/minhsienweng/bertlike-tile-model-gnn-layout-model" target="_blank">notebook</a> focuses on training two models and run them efficiently on limited computing resources (4-core CPUs).</p>
<h1>Context</h1>
<p>Business context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/</a><br>
Data context: <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/data" target="_blank">https://www.kaggle.com/competitions/predict-ai-model-runtime/data</a></p>
<h1>Overview of the Approach</h1>
<p>The solution comprised two models: a GNN model for the layout dataset and a modified BERT model for the tile dataset. The inputs were the graph structures generated by an AI model. In this graph, nodes represented tensor operations (e.g., add, max, reshape, convolution) and edges represented tensors.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F16611574%2F4548b69d2c2e5cbc11e502a30fece82c%2FPresentation1.jpg?generation=1700528423839754&alt=media" alt="Overview"></p>
<h2>TF-GNN Residual Layout model</h2>
<p>I chose the residual model for layout configurations because it can measure the difference between predicted and actual runtime time of each layout configuration. The model uses TensorFlow's graph neural network library (<a href="https://github.com/tensorflow/gnn" target="_blank">TF-GNN</a>) to train efficiently on TPUs. I trained the layout model on TPUs and saved the best model as a pretrained model for prediction. In this notebook, I built four separate models, one for each type of layout dataset: <code>nlp-default</code>, <code>nlp-random</code>, <code>xla-default</code>, and <code>xla-random</code>.</p>
<p>The layout model encodes the layout graph into graph embeddings (<code>node sets</code>, <code>edge sets</code>, and <code>context</code>) and includes 5 hidden layers and a global pooling layer. The model is then trained on 10 epochs, with <code>ListMLE</code> ranking loss as the loss function and ordered pair accuracy (OPA) as the performance metric. The optimizer is AdamW with a learning rate of $10^{-3}$. </p>
<p><em>Things to do</em>: The model can be improved by adjusting the learning rate with cross validation and by pruning irrelevant <code>context</code> to improve memory efficiency. Adding <a href="https://github.com/vijaydwivedi75/gnn-lspe" target="_blank">positional encodings</a> may also help. <a href="https://pyg.org/" target="_blank">PyG</a> library could be used to build and train GNN model. x</p>
<h2>Modified BERT GAN Tile model</h2>
<p>Similar to layout dataset, the tile data is encoded into graph embeddings that include 9 data columns (<code>node_feat</code>, <code>node_opcode</code>, <code>edge_index</code>, <code>config_runtime</code>, <code>config_runtime_normalizers</code>, <code>edges_adjecency</code>, <code>node_config_feat</code>, <code>node_config_ids</code> and <code>selected_idxs</code>).</p>
<p>The tile model is based on the BERT model and uses Graph Attention Networks (<a href="https://arxiv.org/abs/1710.10903" target="_blank">GANs</a>) to give more attention to important parts of the data. This helps improve accuracy by focusing on the most relevant information. The tile model uses a GraphEncoder to encode the tile configuration into graph embeddings and applies a special mask to all layers and heads. This mask is based on the connections between different parts of the graph. The model's loss function compares its predictions to different permutations of the actual results.</p>
<p>Lastly, the model was wrapped with <a href="https://lightning.ai/" target="_blank">Lightning AI</a> library to perform cross-validation using five folds of training and validation datasets. The best model from each fold was saved and then used to further train and predict the testing dataset.</p>
<h1>Details of the submission</h1>
<h2>Training layout model with checkpoints</h2>
<p>I tried to make the BERT model work with the layout dataset, but it needed too much memory (>300GB). So, I used the TF-GNN-based residual model that uses less memory (<30GB). However, training the TF-GNN model is time-consuming. For instance, training one epoch on the 'xla-random' dataset required approximately one hour on CPUs. Training for 10 epochs would exceed the competition's time constraints (>10 hours). Despite utilizing GPUs to accelerate the training process, the training time has little/no speedups. </p>
<p>To speed up training, I used a checkpointing technique to save the model's weights after each epoch. This allowed me to resume training, saving time. The best model was saved and used to predict the test datasets.</p>
<h2>Parallelising the infer loop of tile model</h2>
<p>The infer process for the tile dataset is time-consuming, for example, the model requires approximately 1.81 hours (6,532 seconds) to predict the testing dataset of 844 tile configurations. This is because the infer loop involves running each fold model separately and then merging the results from the five models to get the final output. I tried to speed up the infer loop by using five separate threads to run the inference for each fold's model concurrently. Using a thread pool of three threads, the total infer time is reduced to 58 minutes (3,448 seconds), achieving approximately a 2x speedup on CPUs.</p>
<p>This experiment demonstrates that parallelism techniques can be effectively applied to machine learning models, enabling them to run on standard hardware configurations. This eliminates the need for specialized hardware, making machine learning more accessible to students and researchers with limited computing resources.</p>
<h1>Sources</h1>
<p>The final solution was inspired by the starter notebook by <a href="https://www.kaggle.com/GUSTHEMA" target="_blank">@GUSTHEMA</a> and BERT-like GAT Tile wLayout Dataset by <a href="https://www.kaggle.com/KSMCG90" target="_blank">@KSMCG90</a></p>
<ul>
<li><a href="https://www.kaggle.com/code/gusthema/starter-notebook-fast-or-slow-with-tensorflow-gnn" target="_blank">https://www.kaggle.com/code/gusthema/starter-notebook-fast-or-slow-with-tensorflow-gnn</a></li>
<li><a href="https://www.kaggle.com/code/ksmcg90/bertlike-gat-tile-wlayout-dataset?scriptVersionId=148717592" target="_blank">https://www.kaggle.com/code/ksmcg90/bertlike-gat-tile-wlayout-dataset?scriptVersionId=148717592</a></li>
</ul>
<p>I wrote the solution partly for myself. If I encounter similar problems, I can leverage the knowledge and experience I gained from this competition.</p>
<p>Thank you for your encouragement! 😀</p>
<p>I am still learning about GNNs, but I am interested to explore their potential.</p>
<p>Kaggle provides an excellent platform for learning and experimenting with novel ML models. Most importantly, enjoy the competition and have fun! 😁</p>
<p>Thanks for liking my solution. Please feel free to reach out if you have any questions.</p> |
Google - Fast or Slow? Predict AI Model Runtime | 9th Place Solution: GNN with Compressed Graphs Using Dijkstra’s Algorithm | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you!<br>
Yes, we used GST, but the graph is already small enough that it may not be very useful. </p>
<p>We would like to express our sincere gratitude to our Kaggle teammates and to our hosts for providing the opportunity to participate in such an engaging competition. And thanks to my excellent teammate <a href="https://www.kaggle.com/yoichi7yamakawa" target="_blank">@yoichi7yamakawa</a>. </p>
<p>This was my 7th (and 4th with <a href="https://www.kaggle.com/yoichi7yamakawa" target="_blank">@yoichi7yamakawa</a>) gold medal this year. Wow!</p>
<p>The problem posed was of a type that we had not tackled much before, which made it extremely fascinating to delve into. Here below we outline our solution.</p>
<h1>On Tiles</h1>
<p>We referenced <a href="https://github.com/google-research-datasets/tpu_graphs" target="_blank">GitHub - google-research-datasets/tpu_graphs</a> and public notebooks. <br>
Since the score from the public notebook was already satisfactory, the successful learning of the layout part was the key to this competition.</p>
<h1>On Layout</h1>
<p>We mainly used the implementation of <a href="https://github.com/kaidic/GST/tree/main" target="_blank">GutHub - kaidic/GST</a> as a reference and made modifications that we felt were necessary to improve the score.</p>
<h2>Graph Compression</h2>
<p>During the learning of the layout, the configurable data was limited. Therefore, our implementation only extracted nodes influenced by this and their connected components. <br>
By applying this, our learning efficiency dramatically improved, significantly contributing to the improvement of the score.</p>
<p>Specifically, the following procedures were performed for each data set</p>
<ol>
<li>An undirected graph was constructed using edge_index, and Dijkstra’s algorithm was applied starting from the node with the largest index <code>s</code> (i.e., <code>s=data["node_feat"].shape[0]-1</code>). We chose <code>s</code> as the starting point because many graphs were trees with <code>s</code> as the parent.</li>
<li>The shortest path from <code>s</code> to all the nodes in <code>node_config_ids</code> was calculated, and the union set of nodes and edges in the path was considered as a compressed graph.</li>
</ol>
<p>This compression method reduced the average number of nodes for each layout data from 13894 to 1736 for xla and from 5711 to 570 for nlp. For features of nodes not included in the compressed graph, we simply ignored them completely.</p>
<h2>Preprocessing (log-transform)</h2>
<p>There were times when the learning could not proceed because orders differed depending upon the dimensions of input features. <br>
To cope with this, we underwent log transformation for node features, which consequently made learning proceed smoothly.</p>
<h2>Training Strategy</h2>
<ul>
<li>512 configs were sampled for each data per iteration. The bach_size were 2 or 4.</li>
<li>Trained separate models for the four data types xla-random, xla-default, nlp-random, and nlp-default for 1000 epochs.</li>
<li>The pairwise hinge loss was used (same as original implementation).</li>
</ul>
<h3>CV score</h3>
<ul>
<li>xla random: 0.7</li>
<li>xla default: 0.33</li>
<li>nlp random: 0.96</li>
<li>nlp default: 0.51</li>
</ul>
<h2>Data Specialized for Specific Model Types</h2>
<p>Upon examining the data, we found that architectures (such as BERT, U-Net, ResNet…) could be inferred from IDs or node numbers (or op_codes for test data).<br>
Leveraging this information, we performed learning using data related only to each architecture, which substantially contributed to improving the private score. In addition to the models trained on the entire dataset, we trained models focused on resnet, efficientnet, or bert. Proper EDA is indeed crucial.</p>
<h2>Multiple GNN Architectures</h2>
<p>The TransformerConv and GATConv as Graph conv layers had minimal impact but were useful for ensemble purposes.</p>
<h3>Ensemble</h3>
<p>Although we didn't have sufficient time for meticulous weight tuning, it certainly contributed to steady score improvement (+0.01 - 0.02).</p>
<h3>What Didn't Work</h3>
<ul>
<li>MSELoss as aux-loss</li>
<li>Learning using all nodes</li>
</ul> |
Google - Fast or Slow? Predict AI Model Runtime | Discoveries through the Contest | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the organizers for holding this unique contest! I am currently an undergraduate student in CS and after taking the course on Compiler Design, this contest helped me explore the machine learning driven approaches for compiler optimizations on field to check how AI models run.</p>
<h1><strong>Background</strong></h1>
<p>Reference to the paper <a href="https://arxiv.org/pdf/2308.13490.pdf" target="_blank">"TpuGraphs: A Performance Prediction Dataset on Large Tensor Computational Graphs"</a> gives an overview on the computational graph representation of the programs running on TPUs with a compilation configuration.</p>
<h1><strong>Approach</strong></h1>
<p>The detailed description of the node features, opcode for tiles and layout helps deciding the normalization parameters by noting the estimated time taken for the portion of the program to run given their flow representations. The use of <strong>Graph Convolution Network(GCNConv)</strong> to obtain the most probable runtime order is inspired from its ability to capture local and global information with Parameter Sharing and Transferability.</p>
<h1><strong>Data Preparation</strong></h1>
<p>Weights are assigned in the range [0.0055-0.01] to each feature vector based on the code against a particular instruction. Runtime per node is obtained as a weighted summation of the feature vectors of each node along with any specified connections through the edge values. The normalized config runtime is calculated as a difference of the found <em>config runtime</em> and the <em>config feature vectors</em>, and finally dividing it by the runtime obtained by summing the runtime of all the nodes. The classes to be predicted by the GCN would be the normalized config runtime values obtained as the order of fastest to slowest arranged from 0,n-1. The GCN is trained from the config features as the input, with edge vectors as the connectives. </p>
<h1><strong>Interpretation</strong></h1>
<p>The probabilities of the configuration belonging to a particular class of runtime(0 for the fastest,1,2,etc. specifying the order and n-1 for the slowest) are the outputs obtained as an n*n matrix, where n is the number of configurations. The highest probability obtained for row 'i' at a particular matrix entry pred[i][j] specifies configuration 'i' belongs to class 'j' or the runtime order is the 'j'th fastest. This trained model helps obtaining the predicted runtime classes given nodes of relatable configurations in the test dataset. The nodes bearing the values of the top 5 classes are returned for the tiles dataset. This is similar to the bag-of-words represented as feature vectors used to determine the class of Machine Learning Keywords in the cora dataset.</p>
<h1><strong>Key Takeaways</strong></h1>
<ol>
<li>Reviewing the solution by <a href="https://www.kaggle.com/competitions/predict-ai-model-runtime/discussion/456343" target="_blank">EDUARDO ROCHA DE ANDRADE</a> helped me understand the need for the use of Cross-Config Attention for making this approach more efficient.</li>
<li>The approach also helped obtain the runtime most configurations follow based on the most prominent classes obtained.</li>
</ol> |
Google - Fast or Slow? Predict AI Model Runtime | Kaggle Solution Write-up | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Fast or Slow? Predict AI Model Runtime
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>import pandas as pd<br>
import numpy as np</p>
<p>df1 = pd.read_csv("/kaggle/input/predict-ai-model-runtime/sample_submission.csv")</p>
<p>df1.to_csv("submission.csv", index=False)</p> |
Google - Isolated Sign Language Recognition | 10th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><blockquote>
<p>First, I would like to thank the Armed Forces of Ukraine, Security Service of Ukraine, Defence Intelligence of Ukraine, State Emergency Service of Ukraine for providing safety and security to participate in this great competition, complete this work, and help science, technology, and business not stop and move forward.</p>
</blockquote>
<p>TLDR: Transformer models with embedding based on Linear layers for pose,lips,eye, and STGCN + Linear layer for target hand</p>
<p><strong>Preprocessing</strong><br>
Find target hand using nan in time dimension, flip if need, select poses where target hand is not nan, resize to 16 in time dimension, and finally normalize with</p>
<pre><code>xyz = (xyz - np.nanmean(xyz[:,FACE,:],axis(,))) / np.nanstd(xyz[:,FACE,:],axis=(,))
</code></pre>
<p><strong>Modeling</strong><br>
(All validation scores are based on <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> split on participant id)<br>
After a stuck at 0.75 lb (~0.7 validation), I understand that I need to change strategy.I go back and start modelling only with target hand. After finding best normalization strategy using face I get ~0.69 val score with only hand.<br>
Then I tried to add pose,lips,eyes I get ~0.71 val score. So for me was clear that most of the signal in dominant hand, so i tried to get different representation and ensemble it. Firstly I try to plot target hand and then run 2.5d CNN or TransformerCNN based models, and get with this 0.6 val score only with hand. Then I tried to run STGCN(Spatio-Temporal Graph Convolutional Networks) for target hand and get ~0.66 score. Because CNN gets too much time to process I decide to drop it. So finally after ensembling pose,lip,eye,hand,STGCN(hand) -> attention block i get ~0.72 score</p>
<pre><code>x = torch.cat([
self.pose_emb(x[:,:,:,:].view(B,L,-), x_mask)[],
self.lip_emb(x[:,:,:+,:].view(B,L,-), x_mask)[],
self.reye_emb(x[:, :, + :++, :].view(B, L, -), x_mask)[],
self.leye_emb(x[:, :, ++ :+++, :].view(B, L, -), x_mask)[],
self.hand_emb(x[:, :, +++ :++++, :].view(B, L, -), x_mask)[],
self.graph_emb(x[:, :,+++:++++, :].permute(, , , ).unsqueeze(-)),
self.pos_embed[:L, :].unsqueeze().repeat(B,,)],axis=-)
</code></pre>
<p>Example how i ensemble it.</p>
<p>Then I started to add different augmentations (Here i have to spend definitely more time to increase my score even more), Most of the boost i get from :</p>
<ul>
<li>Mixup</li>
</ul>
<pre><code> np.random.random() < self.args.mixup:
indices = torch.randperm(batch[].size(), device=batch[].device, dtype=torch.long)
beta = np.random.beta(, )
batch[] = beta * batch[] + ( - beta) * batch[][indices]
batch = self.run_logits(batch)
batch[] = beta * self.args.loss(logits=batch[], labels=batch[]) + (
- beta) * self.args.loss(logits=batch[],
labels=batch[][indices])
</code></pre>
<ul>
<li>Copy paste</li>
</ul>
<pre><code> np.random.random() < self.args.cutout:
indices_to_shuffle = torch.randperm(batch[].size(), device=batch[].device, dtype=torch.long)
cutout_len = self.args.cutout_len
(cutout_len) == :
cutout_len = random.uniform(*cutout_len)
sz = (batch[].size() * cutout_len)
ind = np.random.randint(, batch[].size() - sz)
indices_to_cut = torch.(ind, ind+sz, device=batch[].device, dtype=torch.long)
beta = - cutout_len
batch[][:, indices_to_cut] = batch[][indices_to_shuffle][:,indices_to_cut]
batch[][:, indices_to_cut] = batch[][indices_to_shuffle][:,indices_to_cut]
batch = self.run_logits(batch)
batch[] = beta * self.args.loss(logits=batch[], labels=batch[]) + (
- beta) * self.args.loss(logits=batch[],
labels=batch[][indices_to_shuffle])
</code></pre>
<p>After that i get final score ~0.735-0.74 val score and 0.77 lb single model, 0.79 lb ensemble</p>
<p><strong>What didn't work :</strong></p>
<ul>
<li>CNN on dominant hand, didn't get a lot of boost from it.</li>
<li>Different losses based on embedding for words.</li>
<li>Funny idea: Train model with arcface label : (pariticipant_id+sign nearly 5230 labels for full train) , get improvement in val score ~0.02 for val split based on label, because in lb we have samples from train too, i tried to add it to ensemble, but dont get any significant boost so decided to drop it.</li>
</ul>
<p>One more time want to say thanks for every one who support Ukraine in such a hard times.<br>
Slava Ukraini.</p>
<pre><code>X = (xyz[:,:,]-tf.math.reduce_mean(tf.boolean_mask(FACE[:,:,], FACE_NAN[:,:,])))/tf.math.reduce_std(tf.boolean_mask(FACE[:,:,], FACE_NAN[:,:,]))
Y = (xyz[:,:,]-tf.math.reduce_mean(tf.boolean_mask(FACE[:,:,], FACE_NAN[:,:,])))/tf.math.reduce_std(tf.boolean_mask(FACE[:,:,], FACE_NAN[:,:,]))
xyz = tf.stack([X,Y],axis=-)
</code></pre> |
Google - Isolated Sign Language Recognition | 119th Place Solution: Transformer is much much better than GRU! | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First, I want to thank <strong>Kaggle</strong>, <strong>PopSign</strong>, <strong>Google</strong>, and <strong>Partners</strong> for organizing this interesting competition! It provided me a great opportunity to learn and compete with other participants. Second, I want to congratulate to all the winners and other Kagglers for participating in this competition. </p>
<p>To document my learning journey in this competition, I want to share my approach towards this competition. The full inference code is publicly shared as <a href="https://www.kaggle.com/code/nghihuynh/gislr-inference-transformer" target="_blank">GISLR: Inference Transformer</a>.</p>
<hr>
<p><strong>Data Preprocessing:</strong></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F6261540%2Fc5c9a1b33b3c547327ed99a16323a36f%2Ffeature_processing.jpg?generation=1683047881721695&alt=media" alt=""><br>
I applied a simple data preprocessing pipeline with a small modification (without data normalization) from my shared notebook: <a href="https://www.kaggle.com/code/nghihuynh/gislr-eda-feature-processing" target="_blank">GISLR: EDA + Feature Processing</a>. Then, I saved it as featured_preprocessed data for further training.</p>
<p><strong>Model Architecture:</strong></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F6261540%2Ffdf7168215528bb5e1e1289537440306%2Fmodel_architecture.jpg?generation=1683047933576113&alt=media" alt=""></p>
<table>
<thead>
<tr>
<th><strong>Model</strong></th>
<th><strong>Architecture</strong></th>
<th><strong>Original Size</strong></th>
<th><strong>Post Quantization (TFLite FP16 )</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>GRUNet</td>
<td>Landmark embedding:128; Combined embedding:396; GRU units:368; Conv1D: filter: 256, kernel_size: 5</td>
<td>8.78MB</td>
<td>4.4MB</td>
</tr>
<tr>
<td>BiGRUNet</td>
<td>Landmark embedding: 128; GRU units: 768; BiGRU units: 396; Conv1D: filter:396, kernel_size:5</td>
<td>30.84MB</td>
<td>15.4MB</td>
</tr>
<tr>
<td>Transformer</td>
<td>Landmark embedding: 256; Combined embedding: 396; GRU units: 368; Transformer: MHA units: 368, n_head:8, num_block:1; Conv1D: filters:396, kernel_size:5</td>
<td>13.87MB</td>
<td>6.9MB</td>
</tr>
</tbody>
</table>
<p><strong>Cross-Validation</strong>: Participant K-Fold=4<br>
2 sets of validation from fold 3= [62590, 36257, 22343, 37779]</p>
<ul>
<li>GRU: val_set= [22343, 37779]</li>
<li>BiGRU & Transformer: val_set=[37779]</li>
</ul>
<p><strong>Training:</strong><br>
Reduce LR on plateau: factor=0.30, patient=3<br>
Adam optimizer: lr=4.0e-4<br>
Sparse Categorical Loss Entropy <br>
Epochs:100</p>
<p><strong>Results:</strong></p>
<table>
<thead>
<tr>
<th><strong>Model (Ensemble)</strong></th>
<th><strong>Public LB</strong></th>
<th><strong>Private LB</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>GRU-BiGRU-Transformer (selected as final submission)</td>
<td>0.7452</td>
<td>0.82339</td>
</tr>
<tr>
<td>Transformer (not-selected 🙁)</td>
<td>0.73918</td>
<td>0.82484</td>
</tr>
<tr>
<td>Transformer (x2)-GRU (not-selected 🙁)</td>
<td>0.74217</td>
<td>0.82457</td>
</tr>
</tbody>
</table>
<hr>
<p><strong>Conclusion:</strong></p>
<p>Special thanks to the following public notebooks, which helped me a lot during the competition.</p>
<ul>
<li><a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">GISLR TF Data Processing & Transformer Training by Mark Wijkhuizen</a></li>
<li><a href="https://www.kaggle.com/code/aikhmelnytskyy/gislr-tf-on-the-shoulders-ensamble-v2-0-69" target="_blank">GISLR TF: On the Shoulders ENSAMBLE V2 0.69 by Andrij</a></li>
<li><a href="https://www.kaggle.com/code/jvthunder/lstm-baseline-for-starters-sign-language" target="_blank">LSTM Baseline for Starters - Sign Language by JvThunder</a></li>
<li><a href="https://www.kaggle.com/code/hengck23/lb-0-67-one-pytorch-transformer-solution" target="_blank">[LB 0.67] one pytorch transformer solution by hengck23</a></li>
</ul>
<p>Things I tried but didn't work:</p>
<ul>
<li>Different preprocessing (increase number of frames, include more pose, and eyes data, normalize data)</li>
<li>Positional embedding(overfitting)</li>
<li>Attention mask in GRU, BiGRU(overfitting)</li>
</ul> |
Google - Isolated Sign Language Recognition | 11th place solution with code | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to the organizer and Kaggle for hosting this interesting challenge.<br>
Especially I enjoyed this strict inference time restriction. It keeps model size reasonable and requires us for some practical technique.</p>
<h2>TL;DR</h2>
<ul>
<li>Ensemble 5 transformer models</li>
<li>Strong augmentation</li>
<li>Manual model conversion from pytroch to tensorflow</li>
<li>Code is available here -> <a href="https://github.com/bamps53/kaggle-asl-11th-place-solution" target="_blank">https://github.com/bamps53/kaggle-asl-11th-place-solution</a></li>
</ul>
<h2>Overview</h2>
<p>I started from <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> ‘s <a href="https://www.kaggle.com/competitions/asl-signs/discussion/391265" target="_blank">great discussion</a> and <a href="https://www.kaggle.com/code/hengck23/lb-0-67-one-pytorch-transformer-solution" target="_blank">notebook</a>. Thanks for sharing a lot of useful tricks as always!</p>
<p>The changes I made are following;</p>
<ul>
<li>Change model architecture to CLIP transformer in HuggingFace</li>
<li>Decrease parameter size to maximize latency within the range of same accuracy</li>
<li>Some strong augmentations<ul>
<li>Horizontal flip(p=0.5)</li>
<li>Random 3d rotation(p=1, -45~45)</li>
<li>Random scale(p=1, 0.5~1.5)</li>
<li>Random shift(p=1, 0.7~1.3)</li>
<li>Random mask frames(p=1, mask_ratio=0.5)</li>
<li>Random resize (p=1, 0.5~1.5)</li></ul></li>
<li>Add motion features<ul>
<li>current - prev</li>
<li>next - current</li>
<li>Velocity </li></ul></li>
<li>Longer epoch, 250 for 5 fold and 300 for all data</li>
</ul>
<p>For the details, please refer to the code.(planning to upload)</p>
<h2>Model conversion</h2>
<p>I’m too lazy to implement augmentations in tensorflow dataset, so I keep using pytorch training pipeline. But I’ve realized that inference time of the model converted by onnx_tf is way slower than bare tensorflow models. Then I’ve tried some model conversion framework like nobuco, but there were too many errors for some reason. Finally I’ve decided to write the model architecture both in pytorch and tensorflow, then manually port the weight. Thankfully HuggingFace has both pytorch and tensorflow CLIP implementation, this work is easier than I thought. This significantly speeds up inference time and I can put more models when ensembling.</p>
<h2>Ensemble</h2>
<p>I’ve tried to diversify the models as much as possible within the same accuracy range.</p>
<table>
<thead>
<tr>
<th>seed</th>
<th>layers</th>
<th>dim</th>
<th>act</th>
<th>max_len</th>
<th>features</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>2</td>
<td>384</td>
<td>relu</td>
<td>64</td>
<td>lip/hand</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>256</td>
<td>relu</td>
<td>48</td>
<td>lip/hand/eye/motion</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>384</td>
<td>geru</td>
<td>64</td>
<td>lip/hand</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>384</td>
<td>geru</td>
<td>64</td>
<td>lip/hand/eye/motion</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>256</td>
<td>geru</td>
<td>48</td>
<td>lip/hand/eye/motion</td>
</tr>
</tbody>
</table>
<p>The scores are as follows;</p>
<table>
<thead>
<tr>
<th></th>
<th>public</th>
<th>private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Single best model</td>
<td>0.786</td>
<td>0.865</td>
</tr>
<tr>
<td>Ensemble 5 models</td>
<td>0.794</td>
<td>0.87</td>
</tr>
</tbody>
</table>
<h2>What didn’t work;</h2>
<ul>
<li>Normalization matters a lot, so I’ve tried a lot of variants but couldn’t get a better result than simple video mean/std normalization.</li>
<li>More landmarks(like arm, ear, nose or pose)</li>
<li>Conv1d</li>
<li>Knowledge distillation</li>
<li>Model soup</li>
<li>Bigger model</li>
<li>Pretrained model (ex. CLIP pretrained model or pretrain with NTU dataset)</li>
<li>And so on..</li>
</ul>
<h2>Code</h2>
<p><a href="https://github.com/bamps53/kaggle-asl-11th-place-solution" target="_blank">https://github.com/bamps53/kaggle-asl-11th-place-solution</a></p>
<p>Updated to attach a link to the code:)<br>
<a href="https://github.com/bamps53/kaggle-asl-11th-place-solution" target="_blank">https://github.com/bamps53/kaggle-asl-11th-place-solution</a></p> |
Google - Isolated Sign Language Recognition | 12th place solution - MLP Based (Structured Keypoint Pooling network) | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the hosts and the Kaggle team for hosting such an amazing competition.\<br>
Below is my brife solution.</p>
<h2>Model</h2>
<ul>
<li>MLP based. I used a modified model of <a href="https://arxiv.org/abs/2303.15270" target="_blank">the Structured Keypoint Pooling network</a>.</li>
<li>Input joint and bone separately. Bidirectional lateral Connection. Concat after 2 mlp blocks. <ul>
<li>Refered to <a href="https://arxiv.org/abs/2211.01367" target="_blank">Two-Stream Network for Sign Language Recognition and Translation</a></li></ul></li>
</ul>
<h2>Data</h2>
<ul>
<li>Only original data</li>
<li>Lip + Pose (upper body) + Left hand + Right hand</li>
<li>Resize to 64 frames, if long.</li>
<li>Feature: xy (joint or bone), motion of 1&2frame.</li>
<li>So, input shape is [64(frame), (107(joint) + 142(bone)) x 2 (xy) x 3 (+1&2motion)]</li>
<li>Exclude data with an low estimation probability on the training data (1%). [CV: -0.006, publicLB +0.01]</li>
</ul>
<h2>Augmentation</h2>
<ul>
<li>Flip [CV: +0.02]</li>
<li>Scale [CV: + 0.008]</li>
<li>Rotate3d all data [CV: + 0.003]<ul>
<li>Better than Rotate2d by CV 0.002</li></ul></li>
<li>Rotate3d hands individually [CV: +0.002]</li>
<li>Resize frame (only shorten the frame) [CV: + 0.005]</li>
<li>Cut the first or last frame [CV: +0.001]</li>
<li>Swap hand or lip with same sign. [Hand CV: +0.006, Lip CV: + 0.002]</li>
</ul>
<h2>Loss</h2>
<ul>
<li>CrossEntropy (label smoothing 0.4)</li>
</ul>
<h2>What Didn't Work</h2>
<ul>
<li>Word based-label smoothing</li>
<li>Manifold mixup</li>
<li>Shift DA</li>
<li>Adding eye</li>
<li>Pseudo labels</li>
</ul>
<h2>Especially thanks to these kernels</h2>
<ul>
<li><a href="https://www.kaggle.com/code/hengck23/lb-0-67-one-pytorch-transformer-solution" target="_blank">[LB 0.67] one pytorch transformer solution</a> <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a></li>
<li><a href="https://www.kaggle.com/code/roberthatch/gislr-lb-0-63-on-the-shoulders" target="_blank">GISLR [LB 0.63]: On the Shoulders</a> <a href="https://www.kaggle.com/roberthatch" target="_blank">@roberthatch</a></li>
<li><a href="https://www.kaggle.com/code/danielpeshkov/animated-data-visualization" target="_blank">Animated Data Visualization</a> <a href="https://www.kaggle.com/danielpeshkov" target="_blank">@danielpeshkov</a></li>
</ul> |
Google - Isolated Sign Language Recognition | 14th place solution - publicly shared Transformer architecture was so strong! | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Summary</h1>
<p>I thank Kaggle administraror & host for holding this competition. Although struggling with Tensorflow's unfriendly errors and lots of try-and-errors for failing TFLite conversion was really, really tough, these low-layer experience was valuable for me.<br>
Below is my solution writeup of this competition.</p>
<h2>Pipeline</h2>
<p>I tried over 377 different patterns of training models for this competition, however, the best architecture is only minor-changed one from <a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">Mark Wijkhuizen's great public notebook</a>.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4910466%2F980bafe93f77c3d2418f5512ebfb2aa3%2Fpipeline.png?generation=1682985827786639&alt=media" alt=""></p>
<h3>Mixed PostLN & PreLN Architecture</h3>
<p>I tested a) PostLN, b) PreLN, c) Mixed architectures, and found Mixed architecture provides the best result. This architecture was originally (perhaps unintentionally) implemented in the Mark Wijkhuizen's public notebook (in earlier version).</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4910466%2Fe045ca21bb34a220006c06d9306446aa%2Ftransformer_block.png?generation=1682985844553627&alt=media" alt=""></p>
<h3>Other modifications</h3>
<ul>
<li>keep frames with no hands (instead of dropping) in pre-processing.</li>
<li>increase number of layers in the keypoint encoder. With more layers, the accuracy gets better. The 4x layer seetting is the best tradeoff for accuracy and inference time.</li>
<li>set number of hidden units in keypoint encoder independently for each parts (lips=192, left_hand=256, right_hand=256, pose=128). This reduces inference time without losing accuracy.</li>
<li>attach ArcFace layer on training.</li>
</ul>
<h2>Training Setting</h2>
<ul>
<li>loss function: <code>0.5 * ArcFace + 0.5 * CrossEntropy</code> (This setting was shared by <a href="https://www.kaggle.com/code/medali1992/gislr-nn-arcface-baseline" target="_blank">Med Ali Bouchhioua</a>). Using ArcFace loss together with cross entropy loss converges faster, as well as the accuracy gets better.</li>
<li>I tested 50, 80, 100, 120 epochs, but 100 epoch is the best on LB.</li>
<li>Label smoothing (0.20-0.25) can avoid overfitting, but ArcFace is better. Using both label smoothing and ArcFace didn't increase CV/LB.</li>
</ul>
<h3>Data Augmentation</h3>
<p>The augmentation strategy is almost the same as <a href="https://www.kaggle.com/competitions/asl-signs/discussion/391265" target="_blank">that of </a><a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> was shared.</p>
<ul>
<li>handedness swapping (p=0.5)</li>
<li>global 2D Affine transformation (p=0.5, shift=(-0.1, 0.1), rotation=(-30, 30), scale=(0.9, 1.1), shear=(-1.5, 1.5))</li>
<li>random frame masking (p=0.5, mask_ratio=0.75).</li>
</ul>
<p>Frame masking simulates the mis-detection of keypoins. It also act as cutout augmentation in image tasks.</p>
<h2>TFLite Conversion</h2>
<p>When FP16 quantization is applied for the Mark's original implementation, the Transformer block outputs NaN value. So I rewrote transformer block based on <a href="https://www.kaggle.com/code/hengck23/lb-0-73-single-fold-transformer-architecture/notebook" target="_blank">@henck23's implementation</a>.<br>
FP16 quantization made model size about 1/2, without losing model accuracy.</p>
<h3>TTA</h3>
<ul>
<li>apply handedness swapping augmentation to 2/4 of ensemble-seed models</li>
</ul>
<h3>The output TFLite model</h3>
<ul>
<li>model size=26MB</li>
<li>scoring time=56-59 min</li>
</ul>
<h2>Not-worked Experiments</h2>
<ul>
<li>distance/velocity features didn't contribute to increase accuracy.</li>
<li>using synthesized hand pose dataset, I trained z-axis prediction model. I used this model's prediction result for a) 3D-affine transform augmentation and b) sub-task to predict z-axis from key-point encoder's output, but both trials didn't contribute to increase accuracy.</li>
</ul> |
Google - Isolated Sign Language Recognition | 1st place solution - 1DCNN combined with Transformer | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I released my inference notebook. check it if you want! :)</p>
<p>I believe yes, with some modifications.</p>
<p>First of all, I would like to express my gratitude to the Google for hosting this amazing competition. I have always been a big fan of the services, frameworks, and platforms provided by Google.(Colab, GCP, TensorFlow.. all of them are amazing). Without access to these offerings from Google, I wouldn't have been able to win this competition. I would also like to thank all the other participants who shared their ideas. In particular, I gained valuable insights from the ideas shared by <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a>.</p>
<h1>TL;DR</h1>
<p>My solution involved a combination of a 1D CNN and a Transformer, trained from scratch using all training data(competition data only), and used 4x seed ensemble for submission. and I initially started with PyTorch + GPU but later switched to TensorFlow + Colab TPU(tpuv2-8) to ensure compatibility with TensorFlow Lite.</p>
<h1>1D CNN vs. Transformer?</h1>
<p>My hypothesis was that in modeling sequential data, <br>
<strong>if there is a strong inter-frame correlation, 1D CNNs would be more efficient than Transformers.</strong></p>
<p>As in my experiment, the pure 1D CNN easily outperformed the Transformer and as a result, I was able to achieve a public LB score of 0.80 using only the 1D CNN at the end. </p>
<p>However, there still were roles for the Transformer, which could be used on top of the 1D CNN(we can view 1d cnn as some kind of trainable tokenizer).</p>
<h1>Model</h1>
<pre><code> ():
inp = tf.keras.Input((max_len,CHANNELS))
x = tf.keras.layers.Masking(mask_value=PAD,input_shape=(max_len,CHANNELS))(inp)
ksize =
x = tf.keras.layers.Dense(dim, use_bias=,name=)(x)
x = tf.keras.layers.BatchNormalization(momentum=,name=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = TransformerBlock(dim,expand=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = TransformerBlock(dim,expand=)(x)
dim == :
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = TransformerBlock(dim,expand=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = Conv1DBlock(dim,ksize,drop_rate=)(x)
x = TransformerBlock(dim,expand=)(x)
x = tf.keras.layers.Dense(dim*,activation=,name=)(x)
x = tf.keras.layers.GlobalAveragePooling1D()(x)
x = LateDropout(, start_step=dropout_step)(x)
x = tf.keras.layers.Dense(NUM_CLASSES,name=)(x)
tf.keras.Model(inp, x)
</code></pre>
<p>Combining CNN and Transformer is a prevalent idea in recent state-of-the-art models(coatnet, conformer, Maxvit, nextvit…). I started with an 192d 8-layer 1D CNN, then switched to a 192d (3+1)x2 conv-transformer structure, which yielded a +0.01 CV and LB improvement. </p>
<p>The 1D CNN model employed depthwise convolution and causal padding. The Transformer used BatchNorm + Swish instead of the typical LayerNorm + GELU, due to slightly(negligible) lighter inference with the same accuracy.<br>
single model has around 1.85M parameters.</p>
<h1>Masking</h1>
<p><strong>Handling variable-length input correctly was very crucial for ensuring train-test consistency and efficient inference</strong> , as we do not necessarily have to pad the short videos. During training, I used a max_len=384 with padding and truncation, while for inference, I only applied truncation. This approach provided sufficient inference speed and allowed the use of reasonably large models. To accurately apply masking to the 1D CNN, I used causal padding to maintain the mask index. In TensorFlow, masking can be easily implemented using tf.keras.layers.Masking at the beginning of the model. Plus, It is essential to ensure that masking is accurately applied to operations like batch normalization and global average pooling which can be affected by masking.</p>
<h1>Regularization</h1>
<ol>
<li>Drop Path(stochastic depth, p=0.2)</li>
<li>high rate of Dropout (p=0.8)</li>
<li>AWP(Adversarial Weight Perturbation, with lambda = 0.2)</li>
</ol>
<h6> </h6>
<p>As we need to train the model from scratch, regularization technics played a significant role. I used drop_path(0.2, applied after each block), dropout(0.8, applied after GAP) and AWP(Adversarial Weight Perturbation, lambda=0.2) AWP and the dropout applied after epoch 15. All these methods were very crucial for preventing overfitting when training with long epochs(>300). All three methods had a significant impact on both CV and leaderboard scores, and removing any one of them led to noticeable performance drops.</p>
<h1>Preprocessing</h1>
<pre><code> (tf.keras.layers.Layer):
():
().__init__(**kwargs)
self.max_len = max_len
self.point_landmarks = point_landmarks
():
tf.rank(inputs) == :
x = inputs[,...]
:
x = inputs
mean = tf_nan_mean(tf.gather(x, [], axis=), axis=[,], keepdims=)
mean = tf.where(tf.math.is_nan(mean), tf.constant(,x.dtype), mean)
x = tf.gather(x, self.point_landmarks, axis=)
std = tf_nan_std(x, center=mean, axis=[,], keepdims=)
x = (x - mean)/std
self.max_len :
x = x[:,:self.max_len]
length = tf.shape(x)[]
x = x[...,:]
dx = tf.cond(tf.shape(x)[]>,:tf.pad(x[:,:] - x[:,:-], [[,],[,],[,],[,]]),:tf.zeros_like(x))
dx2 = tf.cond(tf.shape(x)[]>,:tf.pad(x[:,:] - x[:,:-], [[,],[,],[,],[,]]),:tf.zeros_like(x))
x = tf.concat([
tf.reshape(x, (-,length,*(self.point_landmarks))),
tf.reshape(dx, (-,length,*(self.point_landmarks))),
tf.reshape(dx2, (-,length,*(self.point_landmarks))),
], axis = -)
x = tf.where(tf.math.is_nan(x),tf.constant(,x.dtype),x)
x
</code></pre>
<p>I used left-right hand, eye, nose, and lips landmarks. For normalization, I used the 17th landmark located in the nose as a reference point, since it is usually located close to the center ([0.5, 0.5]). I used motion feature of lag1 x[:1] - x[1:], and lag2 x[:2] - x[2:](lag > 2 did not help much).</p>
<h1>Augmentation</h1>
<ul>
<li>temporal augmentation</li>
</ul>
<ol>
<li>Random resample (0.5x ~ 1.5x to original length)</li>
<li>Random masking</li>
</ol>
<ul>
<li>Spatial augmentation</li>
</ul>
<ol>
<li>hflip</li>
<li>Random Affine(Scale, shift, rotate, shear)</li>
<li>Random Cutout</li>
</ol>
<h1>Training</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5003978%2Ff23fef7388aa47b7a1e26f6261e6c0a4%2F.png?generation=1683114294544440&alt=media" alt=""></p>
<ul>
<li>Epoch = 400</li>
<li>Lr = 5e-4 * num_replicas = 4e-3</li>
<li>Schedule = CosineDecay with no warmup</li>
<li>Optimizer = RAdam with Lookahead(better than AdamW with optimal parameters)</li>
<li>Loss = CCE with label smoothing=0.1 or just plain CCE</li>
</ul>
<h6> </h6>
<p>final single model result<br>
CV(participant split 5fold): 0.80<br>
public LB: 0.80<br>
private LB: 0.88</p>
<h6> </h6>
<p>Training takes around 4 hours with colab TPUv2-8.</p>
<p>Single model CV was around 0.80 with participant split(5fold) at the end. I ensemble 4 different seed(with some minor differences in training configurations) for the final model and got LB 0.81. By the way, I could see slightly worse score when I submitted 4x size(384d, 16layers) single model with the same settings. I think it can achieve same or better score with better configurations.</p>
<h1>Tried but not worked</h1>
<ul>
<li>GCNs</li>
<li>More Complex augmentations: augmentation based on angle and the distance between the landmarks, grid distortion on temporal, spatial axis, etc.</li>
<li>CutMix, MixUp: Not worked. Main problem was how to define new label with two different length of inputs. I could not find the correct way to implement it.</li>
<li>Knowledge Distillation: I tried to use single 4x sized model and distill it with 4x seed 4x sized model, but I could not manage it to work due to lack of time.</li>
</ul>
<h6> </h6>
<p>I'm always amazed by the fact that we did try each other’s methods, but we came up with different result. I also gave the 2D-CNN(similar to <a href="https://www.kaggle.com/kolyaforrat" target="_blank">@kolyaforrat</a> 's brilliant solution) and pure transformer approaches a try, but due to their initial weak performance and my confidence in my own hypothesis, I didn't dig any deeper. Seeing other teams succeed with the ideas I had trouble with, through their skill and hard work, has been truly inspiring. I've learned a lot through this competition, and I'm grateful for the experience. Thank you all!!! :)</p>
<p>Edit: I made my code public, check <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406978" target="_blank">https://www.kaggle.com/competitions/asl-signs/discussion/406978</a></p>
<p>congratulations for you too! thanks a lot! :)</p>
<p>Im cleaning up my code right now… but right now im not sure which part of my code to be available on the public since it contains bunch of things included in my other projects. </p>
<p>about the softmax, yes I compared it on public LB and without softmax was better so I used it, but it turned out that with softmax was better on private LB and their difference was negligible(around +-0.0004).</p>
<p>thank you and it was an honor for me to compete with you and your team!:)</p>
<p>Masking of PAD is literally for the masking of PAD tokens in the sequence. for example, if the data have the length of 256, 128 PAD tokens are added to match the fixed length of 384 during the training. But we don't want to add the PAD tokens during the inference, as it will significantly increase the inference time. Maybe someone can suggest to use PAD=0 and no masking during training + no padding during inference, this method drops accuracy significantly due to the train-test time inconsistency. So the only choice for us is to mask the PAD part of the inputs during training so that they do not contribute to the calculation of the gradients.</p>
<p>TransformerBlock is originally designed to support variable length inputs, as they use 'attention_mask' when training with PAD tokens, and making it invisible during training. So yes, Transformer block also supports Masking in my implementation, which is trivial.</p>
<p>But the 'masking by causal padding' in the Conv1DBlock I mentioned is bit more trickier to understand. Conv1DLayer does not internally supports masking, as when they used with kernel size > 1, the PAD token will be calculated together in the kernel with neighboring frames. So if we use typical padding='same' argument, the PAD tokens will intrude into the original input sequence's time frames, and makes it much harder to implement masking. On the other hand, the causal padding prevents kernels to see the future frames, and it always preserves the time frame information if strides=1, thus we do not need to additionally handle the position of the mask which is originally generated by the initial tf.keras.layers.Masking layer.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5003978%2Fc658c6591b0eec8bbd97400ddf9d9e7d%2F2023-05-04%20%205.14.16.png?generation=1683144873769874&alt=media" alt=""></p> |
Google - Isolated Sign Language Recognition | 26th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Did you try BatchNorm1d? It was comparable with RMSNorm and also better than the layer norm. Maybe the problem is in batch size.</p>
<h2><a href="https://github.com/dajes/asl-signs" target="_blank">Github with all the code used</a></h2>
<h1>Summary</h1>
<p>The most important part of the solution is the data utilization. Major improvements were from keypoints choice and mixup. External data does not help because it is from a very different distribution. Given data amount does not benefit larger models so ensembles of small models is the way to utilize given constraints to the fullest.</p>
<p>Most augmentations are not helpful, because they prevent model from learning the true data distribution. So only used mirroring and mixup (0.5).</p>
<h1>Inputs to the model</h1>
<p>All models are trained to support sequences of up to 512 frames.</p>
<h2>Preprocessing</h2>
<ul>
<li>Only 2d coordinates are used as 3rd dimension leads to unstable training.</li>
<li>To normalize inputs all keypoints are shifted so that head is located at the origin.</li>
<li>Scaling did not provide any benefit so not used.</li>
<li>All nans are replaced with 0 after normalization.</li>
</ul>
<h2>Chosen keypoints</h2>
<ul>
<li>All (21) hand keypoints</li>
<li>26 face keypoints</li>
<li>17 pose keypoints<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2609709%2Ff5ab58ff94d879f12b65cdd7b06e5d57%2Fbody_keypoints.png?generation=1683103187741075&alt=media" alt=""><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2609709%2Fb8b0058e8ce4f760fb3a0d229ffef1e3%2Fface_keypoints.png?generation=1683103204162958&alt=media" alt=""></li>
</ul>
<h1>Architecture</h1>
<ul>
<li><p>LLaMa-inspired architecture. Most notable improvement comes from much better normalization RMSNorm.</p></li>
<li><p>For all models head dimensions are set to 64</p></li>
<li><p>Single model (Private/Public LB: 0.8543689/0.7702471)</p>
<p>6 heads 5 layers 9.2M parameters</p></li>
<li><p>Ensemble of 3 models (Private/Public LB: 0.8584568/0.7725324)</p>
<p>2 heads 6 layers 1.7M parameters per model</p></li>
</ul>
<p>Larger models could be fit into file size limit, but it would time out during submission.</p>
<h1>Augmentations</h1>
<ul>
<li>The most important is mixup. Significantly improves accuracy and allows for a much longer train before overfitting. Using with alpha=0.5.</li>
<li>Mirroring, does not show much benefit on CV but can't hurt to use.</li>
</ul>
<h2>Augmentations that did not work:</h2>
<ul>
<li>Interpolation over time. Tried using linear and spline interpolation to change the speed of the video and sample at sub-frame coordinates.</li>
<li>Shifting keypoints. Tried shifting keypoints in groups and individually by a small amounts.</li>
<li>Rotating keypoints. Tried rotating keypoints around the head.</li>
<li>Scaling keypoints. Tried scaling keypoint distance to the head.</li>
<li>Mixup of 3+ datapoints. Did not have time to tune the alpha but from the start it did not show any benefit. So stayed with default 2 datapoints mixing.</li>
<li>Rotating and scaling datapoints that are to be mixed up so that it would only mix relative pose and not absolute position.</li>
</ul>
<h1>Training</h1>
<ul>
<li>Lion optimizer is used. Faster convergence and better result (+1%) at the end.</li>
<li>LR is 1e-4 with cosine decay to 1e-5 at the end of training.</li>
<li>Batch size 128</li>
<li>Dropout 0.1</li>
<li>Exponential moving average of weights is used to improve stability of training. Gives 2-4% accuracy boost on CV.</li>
</ul>
<h2>Did not work:</h2>
<ul>
<li>Training model of the data (i.e. trying to predict the next keypoint locations). Tried using different frequency of training the next token predictor and the best frequency turned out to be 0.</li>
<li>Label smoothing. Slower convergence and worse final result on CV.</li>
</ul>
<p>Spatially. Picking the longest common interval between 2 datapoints at a random location if one of the datapoints is longer than the other. Masking out attention from parts which are not mixed as a result</p> |
Google - Isolated Sign Language Recognition | 28th place solution - Using Arcface is not trivial. | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I have noticed that Arcface is frequently used in top solutions of various competitions. <br>
However, when I tried it myself, the convergence was very slow and the performance was not good at result. <br>
In my opinion, the randomly initialized class vectors may not be trained well. <br>
Do you have any tips for using Arcface that you could share with me? <br>
(e.g. Initialized class vector, Choosing margin and scale, normalization … )<br>
In my case, using Arcface in combination with cross entropy was effective.</p>
<p>Thanks to Kaggle and Google for hosting the competition :)<br>
All of the work is done with <a href="https://www.kaggle.com/ydjoo12" target="_blank">@ydjoo12</a> </p>
<h2>Summary</h2>
<p>We used 5-layers Transformer encoder with cross entropy and sub-class Arcface loss and ensemble 6-models trained with different combintation of cross entropy and sub-class Arcface loss.</p>
<h2>Data Preprocessing</h2>
<ul>
<li><p>129 keypoints are used. (21 for each hand, 40 for lip, 11 for pose, 16 for each eye, 4 for nose)</p></li>
<li><p>Only use x and y.</p></li>
<li><p>Pipeline: Augmentations, frame sampling, normalization, feature engineering and 0 imputations for NaN values.</p></li>
<li><p>Frame sampling: When a length exceeds the maximum length, sampling was done at regular intervals up to the maximum length. It is better than center-crop in local CV and it minimized performance degradation while reducing maximum length.</p>
<pre><code>L = (xyz)
L > max_len:
step = (L - ) // (max_len - )
indices = [i * step i (max_len)]
xyz = xyz[indices]
L = (xyz)
</code></pre></li>
<li><p>Normalization: Standardization x and y independently.</p></li>
<li><p>Feature Engineering</p>
<ul>
<li>motion: current xy - future xy</li>
<li>hand joint distance</li>
<li>time reverse difference: xy - xy.flip(dims=[0]): +0.004 on CV</li></ul></li>
</ul>
<h2>Augmentations</h2>
<ul>
<li><p>Flip pose: </p>
<ul>
<li>x_new = f(-(x - 0.5) + 0.5), where f is index change function.</li>
<li>+0.01 on Public LB</li>
<li>xy values are in [0, 1]. Shift to origin by subtracting 0.5 before flip, Back to original coordinates by adding 0.5</li>
<li>There was no performance improvement when not moving to the origin.</li></ul></li>
<li><p>Rotate pose: </p>
<pre><code> ():
radian = np.radians(theta)
mat = np.array(
[[np.cos(radian), -np.sin(radian)], [np.sin(radian), np.cos(radian)]]
)
xyz[:, :, :] = xyz[:, :, :] -
xyz_reshape = xyz.reshape(-, )
xyz_rotate = np.dot(xyz_reshape, mat).reshape(xyz.shape)
xyz_rotate[:, :, :] +
</code></pre>
<ul>
<li>angle between -13 degree ~ 13 degree</li>
<li><a href="https://openaccess.thecvf.com/content/WACV2022W/HADCV/papers/Bohacek_Sign_Pose-Based_Transformer_for_Word-Level_Sign_Language_Recognition_WACVW_2022_paper.pdf" target="_blank">Reference</a></li></ul></li>
<li><p>Interpolation (Up and Down)</p>
<pre><code>xyz = F.interpolate(
xyz, size=(V * C, resize), mode=, align_corners=
).squeeze()
</code></pre>
<ul>
<li>Up-sampling(Down-sampling) up to 125%(75%) of original length </li></ul></li>
</ul>
<h2>Training</h2>
<ul>
<li>5-layers Transformer encoder with weighted cross entropy<ul>
<li>Class weight is based on performance of the class.</li>
<li>Accuracy on LB and CV consistently improved until stacking 4~5 layers.</li>
<li>Public LBs => 1-layer(5 seeds): 0.714, 2-layers(5 seeds): 0.738, 3-layers(5 seeds): 0.748, 4-layers(5 seeds): 0.751</li>
<li>We add dropout layers after self-attention and fc layer based on the PyTorch official code.</li></ul></li>
<li>5-layers Transformer encoder with weighted cross entropy and sub-class Arcface loss.<ul>
<li>loss = cross entropy + 0.2 * subclass(K=3) Arcface</li>
<li>loss = 0.2 * cross entropy + subclass(K=3) Arcface</li></ul></li>
<li>Arcface<ul>
<li>+0.01 on Public LB</li>
<li>Using arcface loss alone resulted in worse performance.</li>
<li>Arcface armed with cross entropy converges much faster and better than cross entropy alone.</li>
<li>Subclass K=3, margin=0.2, scale=32</li></ul></li>
<li>Scheduled Dropout<ul>
<li>+0.002 on CV</li>
<li>Dropout rate on final [CLS] increased x2 after half of training epochs</li></ul></li>
<li>Label Smoothing<ul>
<li>parameter: 0.2</li>
<li>+0.01 on CV</li></ul></li>
<li>Hyper parameters<ul>
<li>Epochs: 140</li>
<li>Max lenght: 64</li>
<li>batch size: 64</li>
<li>embed dim: 256</li>
<li>num head: 4</li>
<li>num layers: 5</li>
<li>CosineAnnealingWarmRestarts w/ lr 1e-3 and AdamW</li></ul></li>
</ul>
<h2>Ensemble</h2>
<ul>
<li>2 different seeds of Transformer with weighted cross entropy<ul>
<li>Single model LB: 0.75</li></ul></li>
<li>2 different seeds of weighted cross entropy + 0.2 * subclass(K=3) Arcface<ul>
<li>Inference: Weighted ensemble of cross entropy and Arcface head.</li>
<li>Single model LB: 0.76</li></ul></li>
<li>2 different seeds of 0.2 * cross entropy + subclass(K=3) Arcface<ul>
<li>Inference: Weighted ensemble of cross entropy and Arcface head.</li>
<li>Single model LB: 0.75</li></ul></li>
<li>6 models ensemble Public LB: 0.779</li>
<li>All models are fp16</li>
<li>Total Size: 20Mb</li>
<li>Latency: 60ms/sample</li>
</ul>
<h2>Working on CV but not included in final submission</h2>
<ul>
<li>TTA<ul>
<li>+0.000x on CV</li>
<li>Sumbission Scoring Error. It might be a memory issue. </li></ul></li>
<li>Angle between bones of each arm<ul>
<li>0.000x on 1 fold. We couldn't fully validate it due to time limits.</li></ul></li>
</ul>
<h2>Not working</h2>
<ul>
<li>GCN embedding layer instead of Linear</li>
<li>Stacking Spatial Attention & Temporal Conv. blocks</li>
<li>Distance between pose keypoints</li>
<li>Removing outlier and Retraining<ul>
<li>We used anlge between learned Arcface subclass vector</li>
<li>About 5% (~4000 samples) are removed</li></ul></li>
<li>Knowledge distillation with bigger Transformer</li>
<li>Stochastic Weight Average</li>
<li>Using all [CLS] in every layer</li>
<li>Average all tokens instead of [CLS] token</li>
<li>Stacking with MLP as meta-learner</li>
</ul> |
Google - Isolated Sign Language Recognition | 2nd Place Solution | Google - Isolated Sign Language Recognition | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Answer <a href="https://github.com/ffs333/2nd_place_GISLR/issues/1#issuecomment-1555364919" target="_blank">here</a></p>
<p>About identification I hope Carno will answer to you later (he found that)</p>
<p>About the ordering:<br>
We arranged them in groups (lips, left hand, pose, right hand), and within groups, in the order in which they are arranged in the raw data. Didn't tried any other orderings. But tried different amount of points and this combination of 80 points was the best</p>
<p>Now just tried to submit single fold solo CNN model and got this score:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F867040d30c2f4535cd33fd19989de3d3%2Ftg_image_380692410.jpeg?generation=1683059371986310&alt=media" alt=""></p>
<p>It's 5th place in public and 4th in private with 17.5 MB and 42 minutes</p>
<p>Thanks!</p>
<p>We tested few times for 5 folds, and with random split OOF scores was almost the same for all folds. That's why after this we trained only fold 0 for all splits. We tried 5 folds, 8 folds, 16 folds. 8 folds version was the best</p>
<p>After finding of some best checkpoint for fold 0 we trained full data checkpoint with the same params.</p>
<p>For getting best ensemble weights we trained all models (eff-b0, bert, deberta) with fold 0 and calculate best weights for ensemble. It was 4 numbers: <br>
<code>cnn_wgt * CNN + trans_wgt * (bert * bert_wgt + deberta * deberta_wgt)</code><br>
Also we have tried manually tune weights on LB score but always that fold0 weights was the best.</p>
<p>You can check how we did it in last 2 commented cells in <a href="https://github.com/ffs333/2nd_place_GISLR/blob/main/kaggle_inference_notebook_example.ipynb" target="_blank">our inference notebook</a></p>
<p>Also sorry about your shakedown, I know that feeling 🙃</p>
<p>Thanks to you 🙃</p>
<p>data is:</p>
<pre><code>sample = train.loc[i]
yy = load_relevant_data_subset(base_dir + sample[])
</code></pre>
<p>In training dataset class we just combine all these <code>yy</code> to list and iterate through it. We keep it RAM for faster training.<br>
And load it like this <code>data = np.load(_cfg.base_path + 'gen_xyz/data.npy', allow_pickle=True)</code><br>
You can see it in repo in <code>GISLR_utils/mixup_data.py</code> <code>DatasetImageSmall80Mixup</code></p>
<p>Sure, it posted <a href="https://github.com/ffs333/2nd_place_GISLR" target="_blank">here</a></p>
<h2>TLDR</h2>
<p>We used an approach similar to audio spectrogram classification using the EfficientNet-B0 model, with numerous augmentations and transformer models such as BERT and DeBERTa as helper models. The final solution consists of one EfficientNet-B0 with an input size of 160x80, trained on a single fold from 8 randomly split folds, as well as DeBERTa and BERT trained on the full dataset. A single fold model using EfficientNet has a CV score of 0.898 and a leaderboard score of ~0.8.</p>
<p>We used only competition data.</p>
<h2>1. Data Preprocessing</h2>
<h3>1.1 CNN Preprocessing</h3>
<ul>
<li>We extracted 18 lip points, 20 pose points (including arms, shoulders, eyebrows, and nose), and all hand points, resulting in a total of 80 points.</li>
<li>During training, we applied various augmentations.</li>
<li>We implemented standard normalization.</li>
<li>Instead of dropping NaN values, we filled them with zeros after normalization.</li>
<li>We interpolated the time axis to a size of 160 using 'nearest' interpolation: <code>yy = F.interpolate(yy[None, None, :], size=self.new_size, mode='nearest')</code>.</li>
<li>Finally, we obtained a tensor with dimensions 160x80x3, where 3 represents the <code>(X, Y, Z)</code> axes. <img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2Fc47290891a7ac6497a6a0c296973f071%2Fdata_prep.jpg?generation=1682986293067532&alt=media" alt="Preprocessing"></li>
</ul>
<h3>1.2 Transformer Preprocessing</h3>
<ul>
<li><p>Only 61 points were kept, including 40 lip points and 21 hand points. For left and right hand, the one with less NaN was kept. If right hand was kept, mirror it to left hand.</p></li>
<li><p>Augmentations, normalization and NaN-filling were applied sequentially.</p></li>
<li><p>Sequences longer than 96 were interpolated to 96. Sequences shorter than 96 were unchanged.</p></li>
<li><p>Apart from raw positions, hand-crafted features were also used, including motion, distances, and cosine of angles.</p></li>
<li><p>Motion features consist of future motion and history motion, which can be denoted as:</p></li>
</ul>
<p>$$<br>
Motion_{future} = position_{t+1} - position_{t}<br>
$$<br>
$$<br>
Motion_{history} = position_{t} - position_{t-1}<br>
$$</p>
<ul>
<li><p>Full 210 pairwise distances among 21 hand points were included. </p></li>
<li><p>There are 5 vertices in a finger (e.g. thumb is <code>[0,1,2,3,4]</code>), and therefore, there are 3 angles: <code><0,1,2>, <1,2,3>, <2,3,4></code>. So 15 angles of 5 fingers were included.</p></li>
<li><p>Randomly selected 190 pairwise distances and randomly selected 8 angles among 40 lip points were included.</p></li>
</ul>
<h2>2. Augmentation</h2>
<h3>2.1 Common Augmentations</h3>
<blockquote>
<p>These augmentations are used in both CNN training and transformer training</p>
</blockquote>
<ol>
<li><p><code>Random affine</code>: Same as <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> shared. In CNN, after global affine, shift-scale-rotate was also applied to each part separately (e.g. hand, lip, body-pose).</p></li>
<li><p><code>Random interpolation</code>: Slightly scale and shift the time dimension.</p></li>
<li><p><code>Flip pose</code>: Flip the x-coordinates of all points. In CNN, <code>x_new = x_max - x_old</code>. In transformer, <code>x_new = 2 * frame[:,0,0] - x_old</code>.</p></li>
<li><p><code>Finger tree rotate</code>: There are 4 root-children pairs in a finger with 5-vertices. E.g. in thumb (<code>[0,1,2,3,4]</code>), these 4 root-children pairs are: <code>0-[1,2,3,4]</code>,<code>1-[2,3,4]</code>,<code>2-[3,4]</code>,<code>3-[4]</code>. We randomly choose some of these pairs, and rotate the children points around root point with a small random angle.</p></li>
</ol>
<h3>2.2 CNN Specific Augmentations</h3>
<ul>
<li><code>Mixup</code>: Implement basic mixup augmentation (only works with CNNs, not transformers).</li>
<li><code>Replace augmentation</code>: Replace some random parts from other samples of the same class.</li>
<li><code>Time and frequence masking</code>: This basic torchaudio augmentation works exceptionally well.</li>
</ul>
<pre><code>freq_m = torchaudio.transforms.FrequencyMasking()
time_m = torchaudio.transforms.TimeMasking()
</code></pre>
<h3>2.3 Augmented Sample Example</h3>
<p>Before augmentation:</p>
<p><img alt="aug1" src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F5d2b97cf6754c5f4063724181bfe7172%2Fbefore_aug.png?generation=1682986332091937&alt=media"> </p>
<p>After augmentation:</p>
<p> <img alt="aug2" src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F516f0790f6f9903ad8943977bc392965%2Fafter_aug.png?generation=1682986413818912&alt=media"> </p>
<h2>3. Training</h2>
<h3>3.1 CNN Training</h3>
<ul>
<li>Train on one fold with a random split (8 folds in total) or the full dataset using the best parameters</li>
<li>Onecycle scheduler with 0.1 warmup.</li>
<li>Use weighted <code>CrossEntropyLoss</code>. Increase the weights for poorly predicted classes and classes with semantically similar pairs (such as kitty and cat)</li>
<li>Implement a hypercolumn for EfficientNet with 5 blocks</li>
</ul>
<h3>3.2 Transformer Training</h3>
<ul>
<li>Train on one fold with a random split (8 folds in total) or the full dataset using the best parameters</li>
<li>Ranger optimizer with 60% flat and 40% cosine annealing learning rate schedule.</li>
<li>A 4-layer, 256 hidden-size, 512 intermediate-size transformer were trained.</li>
<li>A 3-layer model was initialized with 4-layer model's first 3 layers. Knowledge distillation were used in 3-layer model training, in which the 4-layer model is the teacher.</li>
</ul>
<h3>3.3 Hyperparameter Tuning</h3>
<p>Since we trained only one fold and used smaller models, we decided to tune most parameters with Optuna. </p>
<p>Here is the parameters list of CNN training (transformer training has a similar param-list):</p>
<ul>
<li><p>All augmentations probabilities (0.1 - 0.5+)</p></li>
<li><p>Learning rate (2e-3 - 3e-3)</p></li>
<li><p>Drop out (0.1 - 0.25)</p></li>
<li><p>Num of epochs (170-185)</p></li>
<li><p>Loss weights powers (0.75 - 2)</p></li>
<li><p>Optimizer (<code>Lookahead_RAdam</code>, <code>RAdam</code>)</p></li>
<li><p>Label smoothing (0.5 - 0.7)</p></li>
</ul>
<h2>4. Submissions, Conversion and Ensemble</h2>
<ol>
<li><p>We rewrote all our models in Keras and transferred PyTorch weights to them, resulting in a speed boost of around 30%. For transformer model, pytorch-onnx-tf-tflite will generate too much useless tensor shape operations, a fully rewriting can reduce these manually. For CNN model, we rewrote DepthwiseConv2D with a hard-coded way, whose speed is 200%~300% of its original version of tflite DepthwiseConv2D.</p></li>
<li><p>After that, we aggregated all these models in the <code>tf.Module</code> class. Converting directly from Keras resulted in lower speed (don't know why).</p></li>
<li><p>We calculated ensemble weights for models trained on fold 0 using the local fold 0 score and applied these weights to the full dataset models.</p></li>
</ol>
<p>EfficientNet-B0 achieved a leaderboard score of approximately 0.8, and transformers improved the score to 0.81. The final ensemble included:</p>
<ol>
<li>Efficientnet-B0, fold 0</li>
<li>BERT, full data train</li>
<li>DeBERTa, full data train</li>
</ol>
<p>Interestingly, a key feature was using the ensemble without softmax, which consistently provided a boost of around 0.01.</p>
<h2>5. PS. Need <strong>BETTER</strong> TFlite DepthwiseConv2D</h2>
<p>Depthwise convolution models performed very well for these tasks, outperforming other CNN and ViT models (rexnet_100 was also good).<br>
We spent a lot of time dealing with the conversion of DepthwiseConv2D operation. Here are some strange results:</p>
<p>Given a input image with 82x42x32 (HWC), there are two ways to do a 3x3 depthwise convolution in Keras. One is <code>Conv2D(32, 3, groups = 32)</code>, the other is <code>DepthwiseConv2D(3)</code>. However, after converting these two to tflite, the running time of the <code>Conv2D</code> is 5.05ms, and the running time of <code>DepthwiseConv2D</code> is 3.70ms. More strangely, a full convolution <code>Conv2D(32, 3, groups = 1)</code> with FLOPs = HWC^2 only takes 2.09ms, even faster than previous two with FLOPs = HWC.</p>
<p>Then we rewrote the depthwise-conv like this:</p>
<pre><code> ():
out = x[:,:self.H_out:self.strides,:self.W_out:self.strides] * self.weight[,]
i (self.kernel_size):
j (self.kernel_size):
i == j == :
out += x[:,i:self.H_out + i:self.strides,j:self.W_out + j:self.strides] * self.weight[i,j]
self.bias :
out = out + self.bias
out
</code></pre>
<p>The running time of this is 1.24 ms.</p>
<p>In summary, our version (1.24ms) > full <code>Conv2D</code> with larger FLOPs (2.09ms) > <code>DepthwiseConv2D</code> (3.70ms) > <code>Conv2D(C, groups = C)</code> (5.05ms).</p>
<p>However, our version introduced too much nodes in tflite graph, which is not stable in running time. If the tensorflow team has a better implementation of DepthwiseConv2D, we can even ensemble two CNN models, which is expected to reach 0.82 LB.</p>
<p>By the way, EfficientNet with ONNX was ~5 times faster than TFLite.</p>
<h3>Big thanks to my teammates <a href="https://www.kaggle.com/artemtprv" target="_blank">@artemtprv</a> and <a href="https://www.kaggle.com/carnozhao" target="_blank">@carnozhao</a> and congrats with new tiers, Master and GrandMaster!</h3>
<p><a href="https://github.com/ffs333/2nd_place_GISLR" target="_blank">github code</a></p>
<p>Thanks. Congrats to you too!</p>
<p>Yeah, we tried 'nobuco' and some other converters with ONNX. But they are all slower than our keras version. For example with nobuco we was able to add only one transformer model, with our current two transformers</p>
<p>By the way, for us in public LB score for full data train CNN versions was worse and we haven't select it. But in private they were better. But still lower than <a href="https://www.kaggle.com/hoyso48" target="_blank">@hoyso48</a> . That's a pure victory on last hours, GZ!</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F10ba2123e7c100e364688e095a50b569%2Ftg_image_455350557.jpeg?generation=1682988215699105&alt=media" alt=""></p>
<p>Thanks. Congratulations to you too!</p>
<blockquote>
<p>we guessed you were using CNNs but could not get them to match our transformer performances.</p>
</blockquote>
<p>I guess it because we have started CNN at early stage, when transformers didn't get 0.78+ yet, and with simply implementation it has 0.74 LB score (top1 at that moment)</p>
<p>First we trained models with basic CE loss. And then we analyzed the errors of our models as provided <a href="https://www.kaggle.com/kolyaforrat/error-analyse" target="_blank">here</a></p>
<ul>
<li>Bad weights - increase weights of bad predicted classes</li>
<li>Common weights - increase weights of classes which has similar pairs (like kitty and cat)</li>
</ul>
<p>Then just convert it from json to numpy arrays<br>
Powers applied to these weights were just hyper parameter we tuned in optuna. At the beginning we started with wide range from 0 to 3</p>
<p>Also we had problems with samples with low lengths (<8). But we didn't found the solution to predict them better. Tried to train or finetune two models:</p>
<ol>
<li>On train data with increased amount of low length data (<=10)</li>
<li>On only long data (>10)</li>
</ol>
<p>And predict it with if else statements in submission. But it has ~the same score and even little worse</p>
<p>Yeah, they become lower than calculated by errors, but higher that just 1 :)</p>
<p>For example weight for class cat = 2, and it becomes 2**0.75~=1.68 in current run if pw_bad = 0.75</p>
<p>As I said we tuned range of loss weights powers from 0, because we didn't know will they help or not</p>
<p>Thanks!<br>
Sure, that's my last attempts to train, here is 16 random fold split train (accuracy ~0.005 higher than 8 folds split)</p>
<p>LR:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F0d2b6a6b595b8c5e323fb27a16bc74c8%2Ftg_image_762402010.jpeg?generation=1683213719007236&alt=media" alt=""></p>
<p>Train/Val Loss<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F16063ab6e8101a1f6f88c08be4f7548f%2Ftg_image_1545167309.jpeg?generation=1683213729689919&alt=media" alt=""></p>
<p>Accuracy:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2Feee8989b2b68e37bb0279e44984fa101%2Ftg_image_2756323583.jpeg?generation=1683213753844440&alt=media" alt=""></p>
<p>TopK3:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F622f783745ea25768373fdd9d23a1f36%2Ftg_image_3839074706.jpeg?generation=1683213791599040&alt=media" alt=""></p>
<p>Epochs-accuracy-LR:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4212496%2F0cd11d2e85c7097bff3c898d1e598aaa%2Ftg_image_3735457178.jpeg?generation=1683213779294885&alt=media" alt=""></p> |
Google - Isolated Sign Language Recognition | 3rd Place Solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>We used an <strong>ensemble of six conv1d models and two versions of transformers</strong> based on the <a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">public notebook</a>. The key points are <strong>data preprocessing, hard augmentation and ensemble</strong>.</p>
<p>I initially tried to develop my own solution based on the aforementioned public transformer but then I found that the architecture of a model didn’t matter as much as proper work with data and ensembling, so I switched to more simple architectures like <strong>conv1d multilayer models</strong>. I used <code>Keras</code> and utilized all the advantages of native tflite layers like <code>DepthwiseConv1D</code>. My typical model looked like that:</p>
<pre><code>do =
model = Sequential()
model.add(InputLayer(input_shape=(max_len, , )))
model.add(Reshape((max_len, *)))
model.add(Conv1D(, , strides=, padding=, activation=))
model.add(BatchNormalization())
model.add(DepthwiseConv1D(, strides=, padding=, depth_multiplier=, activation=))
model.add(BatchNormalization())
model.add(Conv1D(, , strides=, padding=, activation=))
model.add(BatchNormalization())
model.add(DepthwiseConv1D(, strides=, padding=, depth_multiplier=, activation=))
model.add(BatchNormalization())
model.add(MaxPool1D(, ))
model.add(Conv1D(, , strides=, padding=, activation=))
model.add(BatchNormalization())
model.add(DepthwiseConv1D(, strides=, padding=, depth_multiplier=, activation=))
model.add(BatchNormalization())
model.add(Conv1D(, , strides=, padding=, activation=))
model.add(BatchNormalization())
model.add(DepthwiseConv1D(, strides=, padding=, depth_multiplier=, activation=))
model.add(BatchNormalization())
model.add(GlobalAvgPool1D())
model.add(Dropout(rate=do))
model.add(Dense(, activation=))
model.add(BatchNormalization())
model.add(Dropout(rate=do))
model.add(Dense(, activation=))
model.add(BatchNormalization())
model.add(Dropout(rate=do))
model.add(Dense(, activation=))
</code></pre>
<p>Then two of my colleagues joined me. We had a lot of ideas such as using synthetic data. We found this <a href="https://upcommons.upc.edu/bitstream/handle/2117/94313/TEPP1de1.pdf" target="_blank">paper</a>, created a script which generated synthetic 3D points of a hand parametrized by inner parameters (joints rotations) and camera model and tried to predict the inner parameters of hand by a model, based on the 3d points. And then use this pretrained model to preprocess data. But unfortunately we didn’t have enough time to finish it.</p>
<p>Also we tried to train on additional data (WLASL), found that this dataset gave ~0.005-0.007 increase in local CV score but then we abandoned this idea and haven’t used additional data in our LB submissions.</p>
<h2>Normalization</h2>
<p>We used normalization by this reference points <code>ref = coords[:, [500, 501, 512, 513, 159, 386, 13,]]</code><br>
We didn’t use depth dimension.</p>
<p>We didn’t throw away frames without hands but we took the presence of a hand into account during TTA. </p>
<h2>Augmentation</h2>
<ul>
<li>Random rotation, shift, scale applied globally to each frame</li>
<li>Random small shift added to every point </li>
<li>Combinations of parts - for example we took a hand from one sample and lips from another sample with the same label. This augmentation gave a significant increase in score</li>
<li>CutMix - took parts of samples from different classes. For hand we used 0.7 as a label value, for other parts - 0.3</li>
</ul>
<h2>TTA</h2>
<ul>
<li>Random left/right padding for short sequences</li>
<li>For large sequences of frames we throw away frames with different probability taking into account presence of hands on a frame</li>
</ul>
<p>For different models we used different combinations of points: both hands / only active hand, lips, eyes, top part of pose. For some models we used only every second point of lips/eyes.<br>
For models where we used only one hand we determined which hand is more presented in the video and if it was the left hand we mirrored all points and their coordinates.<br>
We took only <strong>32 frames</strong> for all models except for one where we used 96 frames.</p>
<p>These conv1d models were fast and lightweight so we could ensemble up to six models and still had space and time for additional models and TTA. Ensemble of six such models got <strong>0.7948</strong> on public LB and <strong>0.8711</strong> on private LB.<br>
Then we decided to collaborate with <a href="https://www.kaggle.com/sqqqqy" target="_blank">@sqqqqy</a> who had been working on improving of transformer from a public kernel. His solution looked like that:</p>
<h2>1. Transformer Model</h2>
<ul>
<li>Our transformer model is based on the <a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">public notebook</a>, using different sequence normalization and smaller UNITS size to reduce model parameters.</li>
<li>We implement two kinds of transformer-based model, the first model learn sperate embeddings for each part (just like public notebook), the second learn one embedding with input whole xyz sequence.</li>
<li>1seed of first model score <strong>LB 0.77+</strong>, 1seed of second model score <strong>LB 0.768</strong></li>
</ul>
<h2>2. Preprocessing</h2>
<ul>
<li>We use 20 lip points, 32 eyes points, 42 hands points(left hand and right hand) and 8 pose points.</li>
<li>The input sequence is normalized with shoulder, hip, lip and eyes points.</li>
<li>Filling the NaN values with 0.0</li>
<li>Learn a motion embedding by input $(d_x, d_y, \sqrt{(d_x)^2+(d_y)^2})<em>t$ sequence,
$$
(d_x, d_y)_t = xyz_t - xyz</em>{t-1}<br>
$$</li>
<li>The final embedding is the concat of motion embedding and xyz embedding</li>
</ul>
<h2>3.Augmentation</h2>
<ul>
<li><p>Global augmentation (apply same aug for all frames), including rotation(-10,10), shift(-0.1,0.1), scale(0.8,1.2), shear(-1.0,1.0), flip(apply for some signs)</p></li>
<li><p>Time-based augmentation (apply aug for some frames), random select some frames(1-8) do affine augmentations, random drop frames (fill with 0.0)</p></li>
<li><p>The augmentations greatly improve the score</p></li>
</ul>
<h2>4. HyperParameters</h2>
<ul>
<li>NUM_BLOCKS, 2</li>
<li>NUM_HEAD 8</li>
<li>lr 1e-3 </li>
<li>Optimizer AdamW</li>
<li>Epoch 100</li>
<li>LateDropout 0.2-0.3</li>
<li>Label Smoothing 0.5</li>
</ul>
<p>Six conv1d models with TTA combined with two transformers gave us third place in this competition.</p>
<p>It was surprising for me that it worked. Because we didn't align coordinates of points from different parts so that it resemble a real pose.</p> |
Google - Isolated Sign Language Recognition | 44th Place Silver - How To Improve Best Public Notebook | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><strong>UPDATE:</strong> I shared my code in notebook <a href="https://www.kaggle.com/code/cdeotte/improve-best-public-notebook-lb-0-76" target="_blank">here</a></p>
<p>Hi. To clarify, I am saying "ensemble with itself" is better than "submit single model". Note that I wasn't saying that "ensemble with itself" is better than "ensemble with different NN". </p>
<p>Regarding NN, there is a big difference between submitting 1 NN and 4 NN. The choice for the 4 NN can be same or different, but we get a significant boost using 4 vs. 1. (This is not the case for XGB for example because each XGB is already composed of many trees).</p>
<p>The reason I say "with itself" is "easiest" is because it doesn't require us to design a new NN. However, ensemble with other strong NN will usually perform better than "ensemble with itself".</p>
<p>In actuality, my final sub is 4 models with <code>INPUT_SIZE = 24, 16, 12, 12</code>. Using different sizes versus using <code>INPUT_SIZE = 12, 12, 12, 12</code> achieved slightly better CV and better LB. (And my second final sub is <code>INPUT_SIZE = 8, 10, 12, 16, 24</code>).</p>
<p>Thanks <a href="https://www.kaggle.com/crodoc" target="_blank">@crodoc</a> Congrats on your result.</p>
<p>It is surprising that using only 12 frames works well. I also have a model with <code>INPUT_SIZE = 8</code> and it achieves <code>LB = 0.76</code>. I didn't try smaller but i suspect that 6, 4, 3, 2, 1 might work too with good result.</p>
<p>I guess if we knew sign language then perhaps we (as humans) could look at a few frames and predict which of the 250 words is being signed.</p>
<p>Yes the code from the public notebook with one important change. The public notebook truncates the original video to <code>INPUT_SIZE ** 2</code> frames before interpolation. So to make small <code>INPUT_SIZE<12</code> work we need to increase the truncation. </p>
<p>When <code>INPUT_SIZE = 12</code> then it first truncates all videos to 144 frames before applying interpolation. To make INPUT_SIZE =8 and 10 to work, i do not truncate to 64 and 100. Instead I truncate to 160 and 200 before interpolation.</p>
<p>Note that many of the videos are short. I think 40% are less than 12 frames!</p>
<p><img src="https://raw.githubusercontent.com/cdeotte/Kaggle_Images/main/May-2023/frames.png" alt=""></p>
<p>Thank you Kaggle, Kagglers, PopSign, and Partners for a fun competition! Public notebooks in this competition are very strong! The host said that they need <code>LB >= 0.6</code> to be helpful and the best public notebook scores <code>LB = 0.73</code>! Great job Kagglers!</p>
<p>I joined this competition one week ago, so I didn't have much time to build my own model. Instead, i read the discussions and public notebooks, and attempted to improve the best public notebook. I boosted the best public notebook from public <code>LB = 0.73</code> to <code>LB = 0.77</code> and achieved 44th place Silver.</p>
<h1>Praise for Best Public Notebooks</h1>
<p>I am very impressed with the shared public notebooks</p>
<ul>
<li>Great Transformer model architecture</li>
<li>Selected which 66 Landmarks out of 543 Landmarks are important (hands, lips, pose)</li>
<li>Great preprocessing to convert videos of variable length to small fixed length</li>
<li>Accurate local validation scheme which estimates LB score</li>
</ul>
<h1>Improvements to Best Public Notebook</h1>
<p>After reading the best public notebook, I made the following 11 changes to boost CV and LB <code>+0.03</code> from <code>LB = 0.73</code> to <code>LB = 0.76</code>:</p>
<ul>
<li>Train 1 model => Train 4 models</li>
<li>Add Time Scale augmentation</li>
<li>Ensemble and apply TFLite FP16 quantization</li>
<li>Change the following parameters:</li>
<li>INPUT_SIZE, 64 => 12</li>
<li>BATCH_ALL_SIGNS_N, 4 => 1</li>
<li>N_EPOCHS, 250 => 120</li>
<li>LANDMARK_UNITS, 384 => 224</li>
<li>UNITS, 512 => 376</li>
<li>NUM_BLOCKS, 2 => 3</li>
<li>MLP_RATIO, 4 => 3</li>
<li>MLP_DROPOUT_RATIO, 0.40 => 0.30</li>
<li>remove random frame masking</li>
</ul>
<h1>Published Code</h1>
<p>I published my code <a href="https://www.kaggle.com/code/cdeotte/improve-best-public-notebook-lb-0-76" target="_blank">here</a> for those curious to learn "How To Improve Best Public Notebook" from <code>LB = 0.73</code> to <code>LB = 0.76</code></p>
<h1>My Thought Process</h1>
<p>Most Kagglers are probably curious why and how I discovered these modifications. So let me share my thinking. First, the easiest way to boost CV LB for NN is to ensemble NN with multiple copies of itself (trained with different seeds). So the easiest way to boost public notebook CV LB is to make the model smaller and make the model faster (because this competition has size and time constraints). Then we can include multiple copies of the NN during inference. And each NN we will train with 100% train data.</p>
<p>The first thing i did was reduce <code>LANDMARK_UNITS</code>, <code>UNITS</code>, and <code>MLP_RATIO</code> to reduce the model size. I slowly reduced these parameters to see how small I could go without reducing CV score. It is important to reduce the model to less than 5M (i.e. 5 million) parameters because then we can infer 4 copies of the model within the 40MB size restriction when using FP16. With 40MB size limit, the maximum number of parameters during inference with FP16 is 20M. I also tried less than 4M parameters and 3.3M parameters which allows 5 copies and 6 copies respectively (when using FP16 quantization) </p>
<p>Second, I made the transformer deeper with more transformer blocks. I increased blocks from 2 to 3 which boosted the CV and LB about <code>+0.01</code> or <code>'0.02</code>. Reducing the <code>MLP_RATIO</code> from 4 to 3 significantly reduced the number of model parameters without affecting CV LB so this gave me extra parameters to allow increasing the transformer blocks.</p>
<p>Next, I reduced <code>INPUT_SIZE</code> to speed up the model to make it infer (and train) faster. The parameter <code>INPUT_SIZE</code> is the transformer sequence length. This competition has a inference time constraint of 1 hour (in addition to a 40MB size constraint). Reducing <code>INPUT_SIZE</code> will decrease inference time (and does not affect model size). With sequence length 12, we can easily infer 5+ models under 1 hour.</p>
<p>At this point, i got lucky. Reducing <code>INPUT_SIZE</code> actually boosted the CV and LB by <code>+0.01</code> or <code>+0.02</code> or so. After this I tuned the learning rate, batch size, and learning schedule and found <code>N_EPOCHS = 120</code> and <code>BATCH_ALL_SIGNS_N = 1</code> to be best. Many Kagglers overlook the fact that changing batch size can make a big difference for models. We should always try 0.25x, 0.5x, 2x, 4x batch size and change the learning rate for those experiments to be 0.25x, 0.5x, 2x, 4x respectively. Experiments demonstrate that <code>Batch Size = 256</code> is better than the original <code>Batch Size = 1024</code>. This helped <code>+0.0005</code> or so.</p>
<p>Lastly NN always benefit from more data and data augmentation. I tried external data and many different data augmentation. Using external data did not help me. Regarding augmentation i only got benefit from <code>frame drop out</code> and <code>time scale augmentation</code>. This helped about <code>+0.0005</code> or so. I also tried rotation, scale, shift but this did not help. Flip was not needed since preprocessing normalized all videos to be left handed.</p>
<p>Great question. I added my "thought process" to the discussion post above</p>
<blockquote>
<p>is this SEED that we don't have to set manually?</p>
</blockquote>
<p>Yes, there is nothing for us to change. The "SEED" is for the initialization of NN layers. And the shuffle of batches during training. And the randomness of augmentation etc etc. It is all the random elements during training. So if this "SEED" changes then each NN will be trained differently.</p>
<p>Thank you. I tune everything manually. I change one value and run again. When <code>INPUT_SIZE = 12</code> and <code>N_EPOCHS = 120</code>, each experiment takes about 45 minutes on 1xV100 GPU.</p>
<p>Thanks Junjie. I use GPU outside of Kaggle which gives a big advantage. Locally, I used 8xV100 GPU. So each day, I had 24x8 = 192 hours of GPU compute. In one week I ran about 300 experiments.</p>
<p>Thanks Devastator!</p>
<p>Hi <a href="https://www.kaggle.com/ju7on9" target="_blank">@ju7on9</a> . The original network architecture is defined by</p>
<pre><code># Dense layer units for landmarks
LIPS_UNITS = 224 # WAS 384
HANDS_UNITS = 224 # WAS 384
POSE_UNITS = 224 # WAS 384
# final embedding and transformer embedding size
UNITS = 376 # WAS 512
# Transformer
NUM_BLOCKS = 3 # WAS 2
MLP_RATIO = 3 # WAS 4
</code></pre>
<p>I changed each for a different reason. I lowered <code>MLP_RATIO</code> to shrink the model and I raised <code>NUM_BLOCKS</code> to improve CV and LB. In my discussion, i should say reducing <code>LANDMARK_UNITS, UNITS, and MLP_RATIO</code> gave me extra room to increase <code>NUM_BLOCKS</code>. The point is that increasing <code>NUM_BLOCKS</code> will add 50% more parameters! So we must find a way to significantly reduce the size of the model before we can do that. </p>
<p>The original network had 7.4M parameters and our goal is to get one NN under 5M. We can reduce <code>MLP_RATIO</code> from <code>4 => 3</code> without degrading CV nor LB. This reduces the network to 6.3M parameters. Next decreasing <code>LANDMARK_UNITS</code> from <code>384 => 224</code> reduces to 5.9M parameters. And decreasing <code>UNITS</code> from <code>512 => 384</code> reduces to 3.4M parameters. And neither of these reductions hurt CV nor LB either.</p>
<p>We now have extra room to increase <code>NUM_BLOCKS</code>. Increasing <code>NUM_BLOCKS</code> from <code>2 => 3</code> increases parameters to 4.9M parameters. And boosts CV and LB. We are now under 5M parameters and can safely ensemble 4xNN at <code>FP16</code> within the restriction of 40MB size.</p>
<p>The original notebook (that I forked) trains batch size 1024 for 250 epochs at <code>LR_MAX = 0.001</code> with <code>MLP_DROPOUT_RATIO = 0.40</code>. After adding data augmentation, reducing epochs to 120, and using <code>MLP_DROPOUT_RATIO = 0.30</code> the optimal <code>LR_MAX</code> may be <code>0.004</code> for the original notebook, i forget. Then we reduce the batch size to 256 and reduce the <code>LR_MAX</code> to <code>0.001</code>. So both batch size and learning rate get decreased by <code>0.25x</code>.</p>
<p>Note that other things affect learning rate too like data augmentation, drop out rate, number of epochs, the presence of batch normalization or layer normalization in model architecture, shape of learning schedule, etc etc. If all of these things stay the same that usually adjusting <code>LR_MAX</code> proportionally to adjusting batch size works, however it is only a rule of thumb. </p>
<p>Sometimes when changing batch size we also change other things, and then we might need to search for a new optimal LR. </p>
<p>If training requires only a few epochs (i.e. 1, 2, 3, 4, or 5 epochs) like NLP models, I usually just go with constant LR. Then i look at validation metric and if it increases in the last epoch or two, perhaps I will use <code>LR</code> for the first epochs and <code>LR * 0.1</code> (or 0.3) for the last epochs.</p>
<p>When a model requires many epochs like 20, 40, 80, 160. I usually go with cosine schedule (like this comp). These two techniques work well in most cases.</p>
<p>Thank you HechtJP!</p> |
Google - Isolated Sign Language Recognition | 49th place silver solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you :) </p>
<p>Thank you Kaggle and Pop sign for hosting this competition. I enjoyed working on this problem and learned quite a bit from really good <a href="https://www.kaggle.com/competitions/asl-signs/discussion/391265" target="_blank">discussion posts</a> and <a href="https://www.kaggle.com/datasets/hengck23/asl-demo" target="_blank">code</a> shared - Thank you <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> </p>
<ul>
<li>Pytorch 2.0 (pure pytorch no training library)→ ONNX → TFLITE</li>
<li>Max length i.e. number of frames per video = 256 (Center crop)</li>
<li>Normalization by LIP, SPOSE, Lhand and Rhand (total 90 kepyoints)</li>
<li>Flip augmentation (p=0.5)</li>
<li>Distance, motion and acceleration features (Total 1050)</li>
<li>Model almost same as shared <a href="https://www.kaggle.com/code/hengck23/lb-0-73-single-fold-transformer-architecture]" target="_blank">here</a> - with positional encoding 16, added layernorm in FeedForwardNetwork and 2 fully connected layers with batchnorm, CLS token + mean pooling for final fully connected layer</li>
<li>Loss function cross entropy with label smoothing = 0.75</li>
<li>Epochs 50 - dropout 0.0 for 15 epochs, dropout 0.4 from 15-35 epochs, dropout 0.2 for the remaining</li>
<li>FP16 quantization reduced model size significantly - final size ~26MB and ~60 mins for 5 folds</li>
</ul>
<p>Things that didn’t work </p>
<ul>
<li>External data - It improved by 3-4 ranks but decided to not use it , too messy data and no commercial license</li>
<li>Adding more features, reducing max length, removing data with too high/low number of frames</li>
<li>SWA - couldn’t get it to work</li>
<li>Augment Affine improved CV and private LB but not public LB.</li>
<li>Various hyper parameters like # of encoder blocks, embedding dimension</li>
<li>Arcface Loss - Based on this <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406301" target="_blank">post</a> it seems Arcface loss + label smoothing didn’t work . Should have tried just Arcface and no label smoothing.</li>
<li>Also tried to convert TF model <a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">here</a> to PyTorch</li>
</ul>
<p>Based on private LB scores it seems that data in private LB is much less noisy than training set. </p>
<hr>
<p>My code here - <a href="https://github.com/rashmibanthia/ASL" target="_blank">https://github.com/rashmibanthia/ASL</a></p> |
Google - Isolated Sign Language Recognition | 4th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I would like to thank the organizers and all the competitors. <br>
The overall picture of my solution is shown in the figure below.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1630583%2F2d2c527274d7918f8c3a447a7ffe1863%2Foverview.png?generation=1683110270790469&alt=media" alt=""></p>
<h1>Preprocessing</h1>
<ul>
<li>Use XY coordinates</li>
<li>Normalize the coordinates between the eyebrows to (0,0).</li>
<li>Compare the number of frames detected for the right and left hands, and flip only when the number of frames detected for the right hand is less than that of the left hand (x=-x).</li>
<li>Use XY coordinates of 21 feature points of the right hand (flip left hand) and 40 feature points of the lips, for a total of 122 dimensions.</li>
<li>Delete frames in which the feature points of the hand have not been detected. Therefore, the number of frames for the hand and the number of frames for the lips will be different."</li>
</ul>
<h1>Modeling</h1>
<ul>
<li>I have constructed two types of 1D CNNs. </li>
<li>The first is a model that classifies fixed-length sequences (1DCNN-FixLen). </li>
<li>The second is a model that classifies variable-length sequences (1DCNN-VariableLen). </li>
<li>Both models have a hand backbone, a lips backbone, and a head for classification. </li>
<li>The hand and lips backbones are similar, except that the convolution dimension differs: 128 for the hand backbone and 64 for the lips backbone.</li>
</ul>
<h2>1DCNN-FixLen</h2>
<ul>
<li>Interpolate the sequence to 96. This process is done for both hand and lip feature points.</li>
</ul>
<h3>Backbone</h3>
<ul>
<li>Apply conv 11 times and max_pooling 3 times to reduce sequence length to 12 (=96/(2**3)).</li>
<li>Apply conv to increase the dimension to 512, then apply global_max_pooling.<ul>
<li>Changing global_max_pooling to global_avg_pooling resulted in a significant performance drop. This is probably because important features in the sequence are only included in a few frames. We believe that with global_avg_pooling, these features are averaged out and disappear.</li>
<li>I tried other gating mechanisms such as Gated Linear Unit, but global_max_pooling was the best.</li></ul></li>
</ul>
<h3>Head</h3>
<ul>
<li>Sum the hand features (512 dim) and lips features (512 dim).</li>
<li>Apply 6 fully connected layers (shallow version, stochastic_depth=0.1) or 18 fully connected layers (deep version, stochastic_depth=0.5).<ul>
<li>The deep version ties the parameters of the fully connected layers to prevent model bloat.</li></ul></li>
<li>Classify into 250 classes.</li>
</ul>
<h2>1DCNN-VariableLen</h2>
<h3>Backbone</h3>
<ul>
<li>Apply conv (kernel_size=3) 5 times in total and conv (kernel_size=1) 6 times in total. Unlike above, pooling is not applied.<ul>
<li>Therefore, the size of the receptive field is 11 frames. Since reducing the number of frames further worsened the situation, and increasing the number of frames worsened the situation, it seems that the meaningful sequence was about 11 frames, even if the sequence was long.</li></ul></li>
<li>Apply global_max_pooling after increasing the dimension to 512 with conv.<ul>
<li>During training, the output is masked by sequence length and global_max_pooling is applied. This is because 0-padding is applied to normalize by the maximum length in the batch.</li></ul></li>
</ul>
<h3>Head</h3>
<ul>
<li>Same as FixLen with 1DCNN.</li>
</ul>
<h1>Training</h1>
<ul>
<li>3-fold participant CV.</li>
<li>300 epochs, apply SWA after 15 epochs.</li>
<li>AdamW optimizer.</li>
<li>ArcMarginProduct is used, but only norm normalization of features and weight is applied since margin m=0.</li>
<li>Stochastic Depth, 0.1 or 0.5.</li>
<li>Label Smoothing Loss, epsilon=0.5.</li>
</ul>
<h1>Data Augmentation</h1>
<ul>
<li>Randomly drop frames (p=0.3).</li>
<li>Augment hand position, size, and angle.</li>
<li>Sequence length input to 1DCNN-FixLen is between 64 and 128.</li>
</ul>
<h1>CleanLab</h1>
<ul>
<li>CleanLab was used to remove approximately 5,000 scenes that were considered noise.<ul>
<li>Calculated posterior probabilities with 21-participant-fold and used filter_by="both".</li></ul></li>
<li>The model trained on the cleaned dataset increased LB in the stand-alone model, but not much when ensembling.<ul>
<li>Is it because the data was too clean and the diversity of the models was reduced? I honestly don't know.</li></ul></li>
<li>Also, the gap between CV and LB appeared, so I tried not to be too overconfident.<ul>
<li>In the final submission, CleanLab was applied to only 2 of the 6 ensembles.</li></ul></li>
</ul>
<h1>Extra Experiments</h1>
<p>I did some experiments, including some that weren't included in the final submission. The following two points can be made from this evaluation:</p>
<ul>
<li>CleanLab is effective (+0.003) (compare A and B, D and E).</li>
<li>Large effect of ensembling FixedLen and VariableLen (+0.01) (A0+D).</li>
<li>I couldn't get the prize just by ensembling fixedlen.</li>
</ul>
<table>
<thead>
<tr>
<th>model</th>
<th>Length</th>
<th>head size</th>
<th>cleanlab</th>
<th>seed</th>
<th>Private</th>
<th>Public</th>
</tr>
</thead>
<tbody>
<tr>
<td>A0</td>
<td>fixed</td>
<td>deep</td>
<td>no</td>
<td>0</td>
<td>0.8661</td>
<td>0.7843</td>
</tr>
<tr>
<td>A1</td>
<td>fixed</td>
<td>deep</td>
<td>no</td>
<td>1</td>
<td>0.8682</td>
<td>0.7842</td>
</tr>
<tr>
<td>B0</td>
<td>fixed</td>
<td>deep</td>
<td>yes</td>
<td>5</td>
<td>0.8721</td>
<td>0.7848</td>
</tr>
<tr>
<td>B1</td>
<td>fixed</td>
<td>deep</td>
<td>yes</td>
<td>6</td>
<td>0.8702</td>
<td>0.7862</td>
</tr>
<tr>
<td>C0</td>
<td>fixed</td>
<td>shallow</td>
<td>no</td>
<td>5</td>
<td>0.8651</td>
<td>0.7794</td>
</tr>
<tr>
<td>C1</td>
<td>fixed</td>
<td>shallow</td>
<td>no</td>
<td>6</td>
<td>0.8665</td>
<td>0.7825</td>
</tr>
<tr>
<td>D</td>
<td>variable</td>
<td>deep</td>
<td>no</td>
<td>25</td>
<td>0.8653</td>
<td>0.7812</td>
</tr>
<tr>
<td>E</td>
<td>variable</td>
<td>deep</td>
<td>yes</td>
<td>35</td>
<td>0.8688</td>
<td>0.7840</td>
</tr>
<tr>
<td>F</td>
<td>variable</td>
<td>shallow</td>
<td>no</td>
<td>150</td>
<td>0.8647</td>
<td>0.7794</td>
</tr>
<tr>
<td>A0+A1</td>
<td>fixed</td>
<td>-</td>
<td>no</td>
<td>-</td>
<td>0.8722</td>
<td>0.7905</td>
</tr>
<tr>
<td>B0+B1</td>
<td>fixed</td>
<td>-</td>
<td>yes</td>
<td>-</td>
<td>0.8761</td>
<td>0.7935</td>
</tr>
<tr>
<td>A0+D</td>
<td>-</td>
<td>-</td>
<td>no</td>
<td>-</td>
<td>0.8766</td>
<td>0.7945</td>
</tr>
<tr>
<td>fixedlen only (A0+A1+B0+B1+C0+C1)</td>
<td>fixed</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>0.8774</td>
<td>0.7962</td>
</tr>
<tr>
<td>best sub(A0+B0+B1+C0+E+F)</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>0.8824</td>
<td>0.7999</td>
</tr>
</tbody>
</table>
<p><a href="https://www.kaggle.com/ivanisaev" target="_blank">@ivanisaev</a> </p>
<p>The sign language for this competition was only one-handed.<br>
For this reason, I thought it would be better to focus only on the hands where sign language is being used.<br>
We found that in most cases, the non-signing hand detected fewer frames than the signed hand.</p>
<p>Therefore, if there are more right hand frames than left hand frames, the right hand is used for recognition,<br>
Conversely, if there are more left-hand frames than right-hand frames, flip the X coordinate before recognition.<br>
By doing this, we ensure that all sequences are signed with the right hand.</p> |
Google - Isolated Sign Language Recognition | 5th place solution with code | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Here is a quick overview of the 5th-place solution.</p>
<ol>
<li><p><strong>we applied various augmentations like flip, concatenation, etc</strong><br>
1.1. By applying different augmentations, we can increase the cv by ~ 0.02 (0.76 -> 0.78)</p></li>
<li><p><strong>the model is only a transformer model based on the public kernels</strong><br>
2.1. By increasing the number of parameters, the performance of a single model can be increased to around 0.8 (0.78->0.8) in public LB.<br>
2.1.1. 3 layers of transformer with the embedding size 480.</p></li>
<li><p><strong>Preprocessing by mean and std of single sign sequence</strong><br>
3.1. the preprocessing does affect the final performance. <br>
3.1.1. we tried different ways of calculating the mean and std and found out that using the mean and std of the single sign sequence results in better cv.</p></li>
<li><p><strong>Feature engineering like distances between points</strong><br>
4.1. we selected and used around 106 points (as the public notebook by Heck).<br>
4.2. distances withinpoints of hands/nose/eyes/… are calculated.</p></li>
<li><p><strong>some methods to prevent overfitting like awp, random mask of frames, ema, etc …</strong></p></li>
</ol>
<p>many thanks to my teammates <a href="https://www.kaggle.com/qiaoshiji" target="_blank">@qiaoshiji</a> <a href="https://www.kaggle.com/zengzhaoyang" target="_blank">@zengzhaoyang</a></p>
<p>The source code for training models can be found here : <a href="https://github.com/zhouyuanzhe/kaggleasl5thplacesolution" target="_blank">https://github.com/zhouyuanzhe/kaggleasl5thplacesolution</a></p> |
Google - Isolated Sign Language Recognition | 6th Place Solution - Transformer Tweaking Madness | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to both, the organizers of this competition who offered a fun yet challenging problem as well as all of the other competitors - well done to everyone who worked hard for small incremental increases. </p>
<p>Although I am the one posting the topic, this is the result of a great team effort, so big shoutout to <a href="https://www.kaggle.com/christofhenkel" target="_blank">@christofhenkel</a>.</p>
<h1>Brief Summary</h1>
<p>Our solution is a 2 model ensemble of a MLP-encoder-frame-transformer model. We pushed our transformer models close to the limit and implemented a lot of tricks to climb up to 6th place. <br>
I have 1403 hours of experiment monitoring time in April (that’s 48h per day :)).</p>
<p><strong>Update :</strong> Code is available here : <a href="https://github.com/TheoViel/kaggle_islr" target="_blank">https://github.com/TheoViel/kaggle_islr</a></p>
<h1>Detailed Summary</h1>
<h2>Preprocessing & Model</h2>
<p><a href="https://ibb.co/g3np4jQ"><img src="https://i.ibb.co/80hpYKG/ISLR-drawio-1.png" alt="ISLR-drawio-1"></a></p>
<h3>Preprocessing</h3>
<ul>
<li>Remove frames without fingers</li>
<li>Stride the sequence (use 1 every n frames) such that the sequence size is <code><= max_len</code>. We used <code>max_len=25</code> and <code>80</code> in the final ensemble</li>
<li>Normalization is done for the whole sequence to have 0 mean and 1 std. We do an extra centering before the specific MLP. Nan values are set to 0</li>
</ul>
<h3>Embedding</h3>
<ul>
<li>2x 1D convolutions (<code>k=5</code>) to smooth the positions</li>
<li>Embed the landmark id and type (e.g. lips, right hand, …), <code>embed_dim=dense_dim=16</code></li>
</ul>
<h3>Feature extractor</h3>
<ul>
<li>One MLP combining all the features, and 4 for specific landmark types (2x hands, face, lips)</li>
<li>Max aggregation for hands is to take into account that signers use one hand</li>
<li><code>dim=192</code>, <code>dropout=0.25</code></li>
</ul>
<h3>Transformer</h3>
<ul>
<li>Deberta was better than Bert, but we had to rewrite the attention layer for it to be efficient</li>
<li>To reduce the number of parameters, we use a smaller first transformer, and modify the output layer to upscale/downscale the features. This was key to enable blending 2 models</li>
<li><code>d_in=512</code>, <code>δ=256</code> for <code>max_len=25</code>, <code>δ=64</code> for <code>max_len=80</code>, <code>num_heads=16</code>, <code>dropout=0.05</code> for the first layer, <code>0.1</code> for the other 2</li>
<li>Unfortunately, we did not have any luck with using a pre-trained version of Deberta, for example by importing some of the pretrained weights</li>
</ul>
<h2>Training strategy</h2>
<p><a href="https://imgbb.com/"><img src="https://i.ibb.co/VvT0pVx/ISLR-Train-drawio-1.png" alt="ISLR-Train-drawio-1"></a></p>
<h3>Augmentations:</h3>
<ul>
<li>Horizontal Flip (<code>p=0.5</code>)</li>
<li>Rotate around <code>(0, 0, 0)</code> by an angle between -60 and 60° (<code>p=0.5</code>)</li>
<li>Resizing by a factor in <code>(0.7, 1.3)</code> (<code>p=0.5</code>). We also allow for distortion (<code>p=0.5</code>)</li>
<li>Crop 20% of the start or end (<code>p=0.5</code>)</li>
<li>Interpolate to fill missing values (<code>p=0.5</code>)</li>
<li>Manifold Mixup <a href="https://arxiv.org/abs/1806.05236" target="_blank">[1]</a> (scheduled, <code>p=0.5 * epoch / (0.9 * n_epochs)</code>) : random apply mixup to the features before one of the transformer layer</li>
<li>Only during the first half of the training, since it improved convergence<ul>
<li>Fill the value of the missing hand with those of the existing one (<code>p=0.25</code>)</li>
<li>Face CutMix : replace the face landmarks with those of another signer doing the same sign (<code>p=0.25</code>)</li></ul></li>
</ul>
<h3>Training</h3>
<ul>
<li>100 epochs, <code>lr=3e-4</code>, 25% warmup, linear schedule</li>
<li>Cross entropy with smoothing (<code>eps=0.3</code>)</li>
<li><code>weight_decay=0.4</code>, <code>batch_size=32</code> (x8 GPUs)</li>
<li>OUSM <a href="https://arxiv.org/pdf/1901.07759.pdf" target="_blank">[2]</a>, i.e. exclude the top k (<code>k=3</code>) samples with the highest loss from the computation</li>
<li>Mean teacher <a href="https://arxiv.org/abs/1703.01780" target="_blank">[3]</a> & Knowledge Distillation (see image above). We train 3 models at the same time, and use the distilled one for inference</li>
<li>Model soup <a href="https://arxiv.org/abs/2203.05482" target="_blank">[4]</a> of the last 10 epochs checkpoints</li>
</ul>
<h2>Experiments</h2>
<p><a href="https://ibb.co/MV343Xx"><img src="https://i.ibb.co/jM121pP/cvlb.png" alt="cvlb"></a></p>
<h3>Validation strategy</h3>
<p>We use a Stratified 4-fold, grouped by patient. We had a great CV - LB correlation (see figure), and our best model achieved CV 0.749 - Public 0.795 - Private 0.877. We submitted single models trained on the full dataset, and 2 models for ensembles.</p>
<h3>What worked & reported improvements</h3>
<p>Starting from early April :</p>
<ul>
<li>Baseline : MLP + Bert : LB 0.72</li>
<li>Deberta instead of Bert : CV +0.015 <strong>-> LB 0.73</strong></li>
<li>Improve Feature extractor : CV +0.01 <strong>-> LB 0.74</strong></li>
<li>Flip augmentation : CV +0.015 <strong>-> LB 0.75</strong></li>
<li>Increase model size : CV +0.006 </li>
<li>Two stage training + interp aug : CV + 0.002 ?</li>
<li>Increase model size : CV +0.005 <strong>-> LB 0.76</strong></li>
<li>Deberta Rework : CV +0.005 <strong>-> LB 0.77</strong></li>
<li>OUSM : CV +0.003</li>
<li>Mean Teacher : CV +0.005</li>
<li>Ensemble two distilled models : +0.005 <strong>-> LB 0.78</strong></li>
<li>Conv layers : CV +0.001</li>
<li>Mish <a href="https://arxiv.org/abs/1908.08681" target="_blank">[5]</a> activation instead of ReLU/LeakyReLU : CV +0.001</li>
<li>Warmup 0.1 -> 0.25 : CV +0.001</li>
<li>Model soup : CV +0.001</li>
<li><a href="https://github.com/AlexanderLutsenko/nobuco" target="_blank">Nobuco</a> instead of onnx : 45ms/it -> 38ms/it, this enabled to improve the ensemble </li>
<li>Weight decay 0 -> 0.4 : CV +0.004</li>
<li>Truncation aug : CV +0.001</li>
<li>Manifold mixup : CV +0.002</li>
<li>Different input, model and teacher size for ensemble : CV +0.005 <strong>-> LB 0.79</strong></li>
<li>Centering before the MLP layers : CV +0.004 <strong>-> LB 0.795 (final)</strong></li>
</ul>
<h3>What did not work (for us)</h3>
<ul>
<li>Unfortunately we could not make CNNs work</li>
<li>GCNs, or other architectures that are “sota” for ASL</li>
<li>Heng’s architecture, although others had great results with it</li>
<li>Getting a successful 3-model sub</li>
<li>Relabel the data to reduce label noise</li>
<li>Other augmentations such as noise, dropout, drop frame, shift</li>
<li>Dropout scheduling, custom lr per layer</li>
<li>Pretraining part of the model</li>
<li>Handcrafted graph features (adjacency matrices, edge features)</li>
<li>Adding more landmarks (eyes, eyebrows)</li>
</ul>
<p><em>Thanks for reading !</em></p>
<p>Thanks ! I used draw.io </p>
<p>You're welcome !</p>
<ul>
<li>The mixed mask is the maximum of the two initial masks, in order to allow the transformer to attend everywhere.</li>
<li>You need to have cps close to the same local minimum. In our case lr is quite low during the last 10 epochs (linearly decreased from 4e-5 to 0), and performance does not change a lot. Also, the models are constrained by the teacher model, which weights do not change a lot either as they are updated with an EMA </li>
</ul>
<p>Most tricks were tested on a single fold which took around 1h15 on 8 GPUs (1h without mean teacher). <br>
Then I ran the full 4 folds + fullfit overnight. With distillation it took 2h per fold. </p>
<p>I am lucky to have access to a lot of compute power, which helps a lot :)</p>
<p>Regarding layerwise lr, I couldn't make it work. The overall idea is to give less lr to transformer layers since they have a lot of params improve stability. I tried a few multipliers (x0.5, x0.25), so yes simply trial and error.</p> |
Google - Isolated Sign Language Recognition | 8th place solution ... close but no cigar | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Label smoothing 0.8 ! 😎 … I did not try that. <br>
Understood on the mixup - I tried mixing up the FFN output, I think it helped my CV but hurt public so I gave up. Your chart looks compelling though. Thanks for sharing. </p>
<p>Here is a quick overview of the 8th place solution. </p>
<p>3 transformers models, 2 layers each (384 hidden, 512 hidden ffn), with an ffn encoder (512->384), trained from scratch. LR 8e-4 with cosine schedule trained for ~300 epochs, dropout 0.1, batch size 1024, label smoothing 0.1. Using hands, lips and pose (above waist only). On one transformer all pose and a subset of lips were used for diversity. </p>
<p><strong>Augmentations</strong></p>
<ul>
<li>most important was sequence cutout. On each sample, and each body part (left hand, right hand, lips, pose) with a 0.4 proba convert to nan 5 random slices of 0.15 x SequenceLength. It was hard to overfit with this in.</li>
<li>mirror left</li>
<li>random rotate. </li>
</ul>
<p><strong>Preprocessing</strong></p>
<ul>
<li>Linear interpolation of longer sequences to max length of 96. </li>
<li>Normalise each body part, using min max - I found this better than mean/std. In one model I used mean/std for diversity. </li>
<li>Create time shift delta features on a subset of points, using time shifts of <code>[1, 2, 3, 4, 6, 8, 12, 16]</code>. It was important to forward fill NANs as opposed to 0-fill. </li>
<li>Angle features between xyz position, and xy positions, on a few different joints - corner of mouth, hand, arms. </li>
<li>Some point to point distances, interestingly this did not help much. </li>
</ul>
<p><strong>Tflite</strong><br>
Training was all in pytorch. Converting to tflite, the feature preprocessing was rewritten in tensorflow, and the base models were converted via onnx to tf (this turned out to be a mistake from looking at #2 solution, I should have rewritten the transformer encoder). It was a great opportunity to learn tensorflow. I like it. <br>
A funny thing… doing the following on the pytorch model <code>model = model.half().float()</code> before converting to onnx, gave a good speed up in the final tflite inference. I tried quantizing the pytorch model and it did not further increase the speed. </p>
<p>In the last week I found in preprocessing, normalising points across the whole sequence channel wise gave a good lift. Particularly what I tried to do was for each body part get the channel wise range (max-min), then get the average range over all frames, and use this to normalise the time deltas and the raw coordinates - as opposed to normalising each frame independently. Every time I submitted this it gave a very low score after ~25 mins. I rewrote it in different ways a number of times and it worked with tfilte in kaggle kernels but not when submitted. It was very frustrating at the end. However, I do not think the boost would have brought me into the prize range which was the goal 🤑</p>
<p><strong>Failed attempts</strong></p>
<ul>
<li>Mixup worked ( worked for #9 team), I tried it on the embeddings and it worked ok, . See comments below on mixup.</li>
<li>CNNs with mixup - tried efficientnet and edgenext. I tried on raw points and it did not work, looked like I had an incorrect normalisation from #2 solution. It worked well with an FFN encoder, but was too slow in inference. Looks like I missed to rewrite it into tf, or train in tf. </li>
</ul>
<p>Looking at the logs for efficientnet-b1 it did as well as the transformers using 1e-3 lr with mixup; but this was passing points thru an ffn first which has extra overhead. If I remember correctly when I submitted it was getting 3 or 4 samples per second which was way too slow. Will know next time if I am doing this work with onnx to check netron and the links you mentioned. I gave up too early here. </p> |
Google - Isolated Sign Language Recognition | 9th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks Google and Kaggle for organizing this competition, I hope our solutions will help to create a PopSign product and lower the entering barrier to ASL. </p>
<p>Below I'll give a brief overview of our solution, but before that I want to congratulate my teammate <a href="https://www.kaggle.com/timriggins" target="_blank">@timriggins</a>, with this competition he became Competition Grandmaster! The fun part is that we met during Kaggle Days World Championship in Barcelona last October, once again thanks HP and Kaggle Days for such an opportunity :D</p>
<h2>Model</h2>
<p>We used a transformer model which is very similar to the one <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> shared<br>
Things we changed in architecture/features:</p>
<ul>
<li>1 -> 2 transformer layers (in the final ensemble we used 3 1-layer models and 1 2-layer model)</li>
<li>aside from motion and distance features for hands, our models use lip and eye distances, <br>
absolute hand coordinates <code>abdcoords_r = (rhand - np.nanmean(rhand, 0))</code> <br>
and acceleration <code>racc = np.pad(rh_dist[1:] - rh_dist[:-1], [[0,1], [0,0], [0,0]])</code></li>
</ul>
<p>In two models we used absolute learnable (init. from sinusoidal) positional encoding, <br>
in other two we used learnable 1d-depthwise convolution as pe encoding </p>
<pre><code>self.pe = nn.Conv1d(emb_dim, emb_dim, kernel_size=5, padding=2, stride=1, groups=emb_dim)
## x.shape (B, L, E)
x = self.pe(x.permute(0, 2, 1)).permute(0, 2, 1) + x
</code></pre>
<h2>Augmentations</h2>
<p>Empirically we found following augmentations to be effective:</p>
<ul>
<li>flip-aug</li>
<li>random fps drop <code>xyz = xyz[::2]</code></li>
<li>affine 3d - rotate around spine</li>
<li>early mixup (keypoint space) & manifold mixup (embedding space)</li>
<li>random cuts from start-end of the frame series</li>
<li>interpolation</li>
</ul>
<p>Mix-up was an important augmentation, it allowed us to use longer training schedule w/ cosine scheduler without overfit, all of our models were trained for 150 epochs and converged on the last epoch.</p>
<h2>Pytorch to TFLite conversion</h2>
<p>We used <a href="https://github.com/AlexanderLutsenko/nobuco" target="_blank">nobuco</a>, check it out, it is very intuitive </p>
<h2>Fun bug</h2>
<p>I made a bug in a code that led to a better performance, when implementing a mixup augmentation I did this in the model forward pass function, - </p>
<pre><code>if np.random.randn() < 0.5 and mode_flag == 'train':
x, labels_ohe = self.mixup(x,labels_ohe)
</code></pre>
<p>Later I found out that I'm using normal distribution instead of a uniform one thus if we imagine a PDF of normal disribution, we can say that we're using mixup in ~70% of cases, and when I corrected it, the performance dropped! (so it's better to use mixup with higher probability) </p>
<h2>Results</h2>
<p>Best single model reaches 0.7316 on the hengck participant split, 0.754 if using 4-model ensemble, CV/LB correlation was perfect and each CV improvement translated to both public and private LB. Single model gets scored in approx. 30 mins and ensemble gets scored very close to an hour. I was very worried, since we made last submission on the final day of the competition, but thankfully it didn't timeout :D</p>
<h2>What we tried, but didn't work</h2>
<ul>
<li>External data, - WLASL-pretrain/adding WLASL to train/pretrain on greek sign language dataset, neither of those gave performance boost, even decreased compared to original initialization</li>
<li>Continous MLM/deep predictive coding pretraining - I think that the model is too shallow to benefit for pre-training, I would like to hear from other participants if they used it in their solution</li>
<li>Using 1d-CNN model, - we tried 1d-cnn with depthwise-separable convolutions </li>
<li>Arcface</li>
<li>Train-time overparametrization (for linear layers), concept description can be found in MobileOne paper </li>
</ul> |
Google - Isolated Sign Language Recognition | Solution - Single transformer without val dataset | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the organisers of the PopSign Games and all of the Kaggle community for running such a great competition.</p>
<p>More importantly, my heartfelt thanks go to both <a href="https://www.kaggle.com/markwijkhuizen" target="_blank">@markwijkhuizen</a> and <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a>. MARK contributed a very strong transformer framework, which is the machine learning pipeline for me in this competition. And I will find daily inspiration in <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a>'s discussion post. </p>
<p>As a learner, this competition has taken my machine learning skills a step further. Therefore, I would like to <strong>record the results of my experiment here</strong>.</p>
<h1>Model Architecture</h1>
<p>Shallow networks are the best choice.</p>
<ul>
<li>Single shallow transformer base (Refer to <a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">version 5</a>)<ul>
<li>Added <code>label smoothing</code>.</li>
<li>Used warm up to <code>lr</code>.</li>
<li>Remove all LayerNorm.</li></ul></li>
</ul>
<p>The main changes I have made that have led to improvements:</p>
<ul>
<li>Increase <code>Embedding</code> to 600.</li>
<li>Add a <code>Gaussian noise (0.01)</code> to the FC layer of the Embedding layer.</li>
<li>Increase <code>epoch</code> to 230</li>
<li>Deepens the depth of the last FC layer in the transformer layer.</li>
<li>Late Dropout. 0---0.3---0.1</li>
</ul>
<h1>Feature Engineering</h1>
<p>Feature engineering was the most difficult part of my entire experiment. I came up with a lot of ideas, but most of them ended up being submission errors.</p>
<p>Here is my summary of options that can bring about an uplift and are feasible.</p>
<ul>
<li><p>Use of <code>lips</code>, <code>eyes</code> (regardless of left or right eye), <code>main hand</code> (21 landmarks), and <code>main pose</code> (6 landmarks)</p>
<ul>
<li>Main hand means normalize the right hand to the left hand. The formula is <code>x = 1 - x</code>.</li>
<li>The formula of main pose is <code>x = 1.2 -x</code>. </li></ul></li>
<li><p>Set the input frame count <code>threshold</code> to <strong>48</strong>.</p>
<ul>
<li>Less than that is filled with 0.</li>
<li>More than that is compressed using the <code>Bilinear Interpolation</code> method. (I think it only work well to data where the frame rate is a multiple of 48)</li>
<li>Removal of data with only <code>one frame</code>.</li></ul></li>
<li><p>Add <code>motion feature</code> for coordinate X.</p></li>
<li><p>Add <code>Hand distance feature</code>. (Get inspired by <a href="https://www.kaggle.com/josephzahar" target="_blank">@josephzahar</a>'s <a href="https://www.kaggle.com/code/josephzahar/distance-angle-based-features-using-keras" target="_blank">post</a>)</p>
<ul>
<li>Calculate the Euclidean distance between the discontinuous joints of the hand.</li></ul></li>
</ul>
<p>Hence, the dimensionality of each data in my pipeline is 3 dimensions <code>(x, y, motion)</code>. For the Hand, it is 213<code>(x, y, motion, distance)</code>. </p>
<h1>Augmentation</h1>
<p>There is no need for mirror(flip) augmentation in this pipeline, as the hand is already normalised in the pre-processing.</p>
<p>In augmentation, I only found rotation to be little useful for me. Specifically, I rotated the data with a small sample size (<code>data[-42:]</code>) by 15 degrees up and down. But I think my approach is very poor.</p>
<h1>Future Work</h1>
<ul>
<li>How to distinguish similar words, like awake and wake?</li>
<li>Solve the problem of <code>keras_model_converter.target_spec.supported_types = [tf.float16]</code> not working for me.</li>
<li>How to do rotation correctly?</li>
</ul>
<h1>Summary of Best Solutions (In processing)</h1>
<h3>"How To Improve Best Public transformer basded Notebook" from <a href="https://www.kaggle.com/cdeotte" target="_blank">@cdeotte</a></h3>
<ul>
<li><p>Original Post</p>
<ul>
<li><a href="https://www.kaggle.com/competitions/asl-signs/discussion/406302" target="_blank">https://www.kaggle.com/competitions/asl-signs/discussion/406302</a></li></ul></li>
<li><p>Corresponding Notebook</p>
<ul>
<li><a href="https://www.kaggle.com/code/cdeotte/improve-best-public-notebook-lb-0-76" target="_blank">https://www.kaggle.com/code/cdeotte/improve-best-public-notebook-lb-0-76</a></li></ul></li>
<li><p>Keypoints: </p>
<ul>
<li>Reduce batch size and increse transformer block.</li>
<li>Ensemble with different model seeds.</li></ul></li>
<li><p>All changes</p>
<ol>
<li><p>Train 1 model => Train 4 models</p></li>
<li><p>Add Time Scale augmentation</p></li>
<li><p>Ensemble and apply TFLite FP16 quantization</p></li></ol>
<p>Change the following parameters:</p>
<ol>
<li><p>INPUT_SIZE, 64 => 12</p></li>
<li><p>BATCH_ALL_SIGNS_N, 4 => 1</p></li>
<li><p>N_EPOCHS, 250 => 120</p></li>
<li><p>LANDMARK_UNITS, 384 => 224</p></li>
<li><p>UNITS, 512 => 376</p></li>
<li><p>NUM_BLOCKS, 2 => 3</p></li>
<li><p>MLP_RATIO, 4 => 3</p></li>
<li><p>MLP_DROPOUT_RATIO, 0.40 => 0.30</p></li>
<li><p>Remove random frame masking</p></li></ol></li>
<li><p>The results of the experiments combined with those tricks</p>
<ul>
<li><p>Just use a-i parameters changes in my solution (Step i is necessary, otherwise it would be by gradient messages.). </p>
<ul>
<li>Public: 0.7525. </li>
<li>Private: 0.8340</li></ul></li>
<li><p>Ensemble 2 seed models without quantization. (Surprised by this decline, I am looking into the reasons for it.)</p>
<ul>
<li>Ensemble Public: 0.7443 <ul>
<li>Model0 Public: 0.73</li>
<li>Model1 Public: 0.7314</li></ul></li>
<li>Ensemble Private: 0.8276<ul>
<li>Model0 Private: 0.814</li>
<li>Model1 Private: 0.816</li></ul></li>
<li><strong>I have found the reason. I change <code>lr</code> to <code>0.4*lr</code>, cause <code>BATCH_ALL_SIGNS_N</code> reduces from 4 to 1. This action was wrong, because I use rotation augmentation before training. In other words, all changing variables can affect the choice of <code>lr</code>. If those variables stay same but <code>batch_size</code>, We need to make the change in <code>batch_size</code> proportional to the change in <code>lr</code>.</strong> (Answer from this <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406302#2248253" target="_blank">post</a>)<br>
After cancelling the change of <code>lr</code>. The result is shown below</li>
<li>Ensemble Public: 0.7683 </li>
<li>Ensemble Private: 0.8445</li></ul></li></ul></li>
<li><p>To be resolved</p>
<ul>
<li><p>What is Time Scale augmentation? and How to remove random frame masking?</p></li>
<li><p>Why the learning rate is proportional to the batch size?</p>
<ul>
<li>Answer: This is correct with the other model parameters held constant. However, this is wrong if other variables (epoch, dropout rate, etc.) change.</li></ul></li>
<li><p>Where this from "Accurate local validation scheme which estimates LB score" ?</p></li></ul></li>
</ul>
<h1>Rule of thumbs</h1>
<h2>How to choose learning rate</h2>
<ul>
<li><p><a href="https://www.kaggle.com/code/isbhargav/guide-to-pytorch-learning-rate-scheduling/notebook" target="_blank">https://www.kaggle.com/code/isbhargav/guide-to-pytorch-learning-rate-scheduling/notebook</a></p></li>
<li><p>From this <a href="https://www.kaggle.com/competitions/asl-signs/discussion/406302#2248264" target="_blank">post</a></p></li>
</ul>
<blockquote>
<p>If training requires only a few epochs (i.e. 1, 2, 3, 4, or 5 epochs) like NLP models, I usually just go with constant LR. Then i look at validation metric and if it increases in the last epoch or two, perhaps I will use <code>LR</code> for the first epochs and <code>LR * 0.1</code> (or 0.3) for the last epochs.</p>
<p>When a model requires many epochs like 20, 40, 80, 160. I usually go with cosine schedule (like this comp). These two techniques work well in most cases.</p>
</blockquote>
<p>Thank you. Your thoughts bring me a lot.</p>
<p>Firstly, there are time constraints and size constraints, and you need to make a lightweight model.<br>
Secondly, there is the large scope for manipulation that a shallow network brings. You can do operations such as ensemble.<br>
However, that's only relative to the context of this competition.</p> |
Google - Isolated Sign Language Recognition | Top 8% Bronze Medal Solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><blockquote>
<p><strong>Many congratulations to all the winners in this competition. Huge thanks to all the discussion topics, public notebooks and datasets - most (if not all of) of my learning came from them.</strong></p>
</blockquote>
<p>First I would like to thank the organizers of this wonderful competition. </p>
<p>To say that I learned a lot by competing in this competition would really be an understatement. I wanted to take on the challenge of using Tensorflow in this competition and boy did it test me. If there was one thing that gave me hope in this competition it was <a href="https://www.kaggle.com/markwijkhuizen" target="_blank">@markwijkhuizen</a>'s amazing public <a href="https://www.kaggle.com/code/markwijkhuizen/gislr-tf-data-processing-transformer-training" target="_blank">notebook</a>. It was the foundation to my entire work in this competition.</p>
<p>Initially I was using my own Transformer architectures in this competition which were not bad themselves but as <a href="https://www.kaggle.com/tatamikenn" target="_blank">@tatamikenn</a> pointed it, the public notebooks had really good Transformer architectures, with a few tweaks and code cleanups I was able to extract good results both on CV and LB, this gave me a significant increase in CV and LB right on my first experiment. </p>
<blockquote>
<p>I have open sourced the code base on GitHub -> <a href="https://github.com/abhinand5/isolated-sign-language-recognition" target="_blank">https://github.com/abhinand5/isolated-sign-language-recognition</a>. </p>
<p>Leave a ⭐️ if you like my work.</p>
</blockquote>
<h3>What worked for me?</h3>
<ul>
<li>Flip augmentation (<code>aug_prob = 0.4</code>)</li>
<li>10 Fold Cross Validation</li>
<li><code>label_smoothing = 0.3</code></li>
<li><code>embed_dim = 256</code></li>
<li><code>input_size = 32</code></li>
<li><code>num_transformer_blocks = 2</code> (Using 1 was under-fitting and 3 was over fitting even after several experiments of trying to tune)</li>
<li>Attention heads: <code>MHA_HEADS = 4</code> and <code>MHA_HEADS = 8</code></li>
<li>Train on the entire dataset before submission</li>
<li>FP16 Quantization</li>
<li>GeLU activation</li>
</ul>
<h3>What did NOT work for me?</h3>
<ul>
<li><code>input_size = 64</code></li>
<li>Knowledge Distillation (wasted a lot of time in this)</li>
<li>Rotate augmentations (degraded CV and LB)</li>
<li>Adding Gaussian noise to the inputs (degraded CV and LB)</li>
<li>Removing <code>LayerNorm</code> from Transformer blocks (although the arch is shallow it did not work for me)</li>
<li>Strip Pruning </li>
<li>Dynamic Range Quantization (increased the inference time)</li>
<li>2D Affine transforms</li>
</ul>
<h3>Final Solution:</h3>
<p>There were two different model architectures in the final solution. </p>
<p><strong>Dataset:</strong> Only Competition Data</p>
<p><strong>Model 1:</strong></p>
<ul>
<li>Training <code>epochs = 50</code></li>
<li>Add LayerNorm</li>
<li>CV Strategy: <code>StratifiedGroupKFold(k=10)</code></li>
<li>Optuna tuning -> Best OOF on all folds</li>
<li><code>SEED = 555</code></li>
<li>Ensemble of Best Folds: <code>[3,6,7,9]</code> (based on OOF score)</li>
<li><code>QUANTIZE_MODEL = True</code></li>
<li><code>QUANT_METHOD = "float16"</code></li>
<li>No Augmentations</li>
</ul>
<p>Below is the complete model conf:</p>
<pre><code>
</code></pre>
<p><strong>Model 2:</strong></p>
<ul>
<li>Training <code>epochs = 100</code></li>
<li>Add LayerNorm</li>
<li>Single Split -> Optuna Tuning -> Use best hyper params to train on entire train data</li>
<li><code>SEED = 555</code></li>
<li><code>QUANTIZE_MODEL = True</code></li>
<li><code>QUANT_METHOD = "float16"</code></li>
<li>Flip Augmentations (<code>aug_prob=0.4</code>)</li>
</ul>
<p>Below is the complete model conf:</p>
<pre><code>
</code></pre>
<p><strong>Submission:</strong><br>
The submission is a simple ensemble of 5 models </p>
<pre><code>Model 1 (folds=[3,6,7,9]) + Model 2
Private Score: 0.82815
Public Score: 0.73896
</code></pre>
<p>Ensembling code can be found below:</p>
<pre><code> (tf.Module):
():
(TFLiteEnsembleModel, self).__init__()
self.preprocess_layer = preprocess_layer
self.models = models
self.weights = weights [/(models)] * (models)
self.weights = tf.reshape(self.weights, (-, ))
():
x, non_empty_frame_idxs = self.proprocess_inputs(inputs)
outputs = []
_model self.models:
output = _model({ : x, : non_empty_frame_idxs })
outputs.append(output)
outputs = tf.concat(outputs, axis=)
weighted_outputs = outputs * self.weights
weighted_sum = tf.reduce_sum(weighted_outputs, axis=, keepdims=)
outputs = tf.squeeze(weighted_sum, axis=)
{: outputs}
():
x, non_empty_frame_idxs = self.preprocess_layer(inputs)
x = tf.expand_dims(x, axis=)
non_empty_frame_idxs = tf.expand_dims(non_empty_frame_idxs, axis=)
x, non_empty_frame_idxs
</code></pre> |
Google - Isolated Sign Language Recognition | 🥈18th Place Solution🥈 | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google - Isolated Sign Language Recognition
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>TLDR</h1>
<p>Based on my experiment, it seems that the most significant factors contributing to improved performance were <strong>regularization</strong>, <strong>feature processing</strong> and <strong>embedding_layer</strong>. The final ensemble model consisted of various input features and models, including Transformer, MLP, and GRU.<br>
<br></p>
<h1>Data Processing</h1>
<p>Out of the 543 landmarks in the provided raw data, a total of 115 landmarks were used for hands, poses, and lips. Input features were constructed by concatenating xy(z), motion, and distance, resulting in a final input feature size of 1196. Initially, using only the distance feature of hand data was employed, but the significant performance improvement (CV +0.05) was achieved by adding the distance feature of pose and lip data. </p>
<pre><code>feature = tf.concat([
tf.reshape(xyz_hand[:, :21, :3], [-1, 21 * 3]),
tf.reshape(xyz_pose[:, 21:46, :2], [-1, 25 * 2]),
tf.reshape(xyz_lip[:, 46:66, :2], [-1, 20 * 2]),
tf.reshape(motion_hand[:, :21, :3], [-1, 21 * 3]),
tf.reshape(motion_pose[:, 21:46, :2], [-1, 25 * 2]),
tf.reshape(motion_lip[:, 46:66, :2], [-1, 20 * 2]),
tf.reshape(distance_hand, [-1, 210]),
tf.reshape(distance_pose, [-1, 300]),
tf.reshape(distance_outlip, [-1, 190]),
tf.reshape(distance_inlip, [-1, 190]),
], axis=-1)
</code></pre>
<p>Additionally, the hand with fewer NaN values was utilized, and the leg landmarks were removed from the pose landmarks. Based on this, two versions of inputs were created. The first version only utilized frames with non-NaN hand data, while the second version included frames with NaN hand data. The former had a max_length of 100, and the latter had a max_length of 200.</p>
<pre><code>cond = lefth_sum > righth_sum
h_x = tf.where(cond, lefth_x, righth_x)
xfeat = tf.where(cond, tf.concat([lefth_x, pose_x, lip_x], axis = 1), tf.concat([righth_x, pose_x, lip_x], axis = 1))
</code></pre>
<p><br></p>
<h1>Augmentation</h1>
<p>The hand with fewer NaN values was utilized, and both hands were flipped to be recognized as right hands in the model, which actually contributed to a performance improvement of about 0.01 in CV.</p>
<pre><code># x-axis mirroring
cond = lefth_sum > righth_sum
xfeat_xcoordi = xfeat[:, :, 0]
xfeat_else = xfeat[:, :, 1:]
xfeat_xcoordi = tf.where(cond, -xfeat_xcoordi, xfeat_xcoordi)
xfeat = tf.concat([xfeat_xcoordi[:, :, tf.newaxis], xfeat_else], axis = -1)
</code></pre>
<p>I did not observe that flip, rotate, mixup, and other augmentation techniques contributed to performance improvement in CV, so I supplemented this by ensembling the models of the two versions of inputs mentioned earlier.<br>
<br></p>
<h1>Model</h1>
<p>Prior to being utilized as inputs for the transformer model, the input features, namely xy(z), motion, and distance, underwent individual processing through dedicated embedding layers. Compared to the scenario where features were not processed independently, a performance improvement of 0.01 was observed in the CV score when the features were treated independently.</p>
<pre><code># embedding layer
xy = xy_embeddings(xy)
motion = motion_embeddings(motion)
distance_hand = distance_hand_embeddings(distance_hand)
distance_pose = distance_pose_embeddings(distance_pose)
distance_outlip = distance_outlip_embeddings(distance_outlip)
distance_inlip = distance_inlip_embeddings(distance_inlip)
x = tf.concat([xy, motion, distance_hand, distance_pose, distance_outlip, distance_inlip], axis=-1)
x = relu(x)
x = fc_layer(x)
x = TransformerModel(input_ids = None, inputs_embeds=x, attention_mask=x_mask).last_hidden_state
</code></pre>
<p><br></p>
<p>For Transformer models, I used huggingface's RoBERTa-PreLayerNorm, DeBERTaV2, and GPT2. The input was processed independently for xyz, motion, and distance, and then concatenated to form a 300-dimensional transformer input. The mean, max, and std values of the Transformer output were then concatenated to obtain the final output.</p>
<pre><code># pooling function
def get_pool(self, x, x_mask):
x = x * tf.expand_dims(x_mask, axis=-1) # apply mask
nonzero_count = tf.reduce_sum(x_mask, axis=1, keepdims=True) # count nonzero elements
max_discount = (1-x_mask)*1e10
apool = tf.reduce_sum(x, axis=1) / nonzero_count
mpool = tf.reduce_max(x - tf.expand_dims(max_discount, axis=-1), axis=1)
spool = tf.sqrt((tf.reduce_sum(((x - tf.expand_dims(apool, axis=1)) ** 2) * tf.expand_dims(x_mask, axis=-1), axis=1) / nonzero_count) + 1e-9)
return tf.concat([apool, mpool, spool], axis=-1)
</code></pre>
<p>In addition to the Transformer model, simple linear models and GRU models also achieved similar performance to the Transformer model, so I ensembled these three types of models.<br>
<br></p>
<h1>Training</h1>
<ul>
<li>Scheduler : lr_warmup_cosine_decay </li>
<li>Warmup Ratio : 0.2 </li>
<li>Optimizer : AdamW </li>
<li>Weight Decay : 0.01</li>
<li>Epoch : 40</li>
<li>Learning Rate : 1e-3 </li>
<li>Loss Function : CrossEntropyLoss </li>
<li>Smoothing Value : 0.65 ~ 0.75</li>
</ul>
<p><br></p>
<h1>Regularization</h1>
<p>During model training, there are three primary regularization techniques that have made significant contributions to both improving convergence speed and final performance</p>
<ul>
<li><p>Weight normalization applied to the final linear layer(<a href="https://arxiv.org/abs/1602.07868" target="_blank">paper</a>)</p>
<pre><code>final_layer = torch.nn.utils.weight_norm(nn.Linear(hidden_size, 250))
</code></pre></li>
<li><p>Batch normalization applied before the final linear layer</p>
<pre><code># head
x = fc_layer(x)
x = batchnorm1d(x)
x = relu(x)
x = dropout(x)
x = final_layer(x)
</code></pre></li>
<li><p>High weight decay value with the AdamW<br>
<br></p></li>
</ul>
<h1>TFLite Conversion</h1>
<p>In the early stages of the competition, I worked with PyTorch, which meant I had to deal with numerous errors when converting to TFLite, and ultimately failed to handle dynamic input shapes. In the latter stages of the competition, I began working with Keras, and the number of errors when converting to TFLite was significantly reduced.<br>
<br></p>
<h1>Didn't Work</h1>
<ul>
<li>Adding the distance feature contributed to performance improvement, but adding angle and direction features did not.</li>
<li>Increasing the number of transformer layers did not contribute to performance improvement.</li>
<li>I attempted to model the relationships between landmark points using Transformers or GATs, but the inference speed of the model became slower, and the performance actually decreased.</li>
<li>Bert-like pretraining (MLM) for XYZ coordinates did not improve performance with the provided data in the competition.<br>
<br></li>
</ul>
<h1>Learned</h1>
<p>I am currently serving in the military in South Korea. During my army training, I learned a lot while coding in between. I was amazed by the culture of Kagglers sharing various ideas and discussing them. It's really cool that something bigger and better something can be born through this community, and I also want to participate in it diligently in the future. Thank you for reading my post.<br>
<br></p>
<h1>Code</h1>
<p><a href="https://github.com/siwooyong/Google-Isolated-Sign-Language-Recognition" target="_blank">https://github.com/siwooyong/Google-Isolated-Sign-Language-Recognition</a><br>
<br></p>
<p>Thank you!!! bro👍👍👍</p>
<p>In my opinion, the reason why there are many errors in the process of converting PyTorch to TFLite is that the process itself is quite lengthy. Unlike Keras models, which can be directly converted using specific code, </p>
<pre><code>converter = tf.lite.TFLiteConverter.from_keras_model(KerasModel)
tflite_model = converter.convert()
</code></pre>
<p>PyTorch models go through multiple steps, such as conversion to ONNX, ONNX to TensorFlow, and then TensorFlow to TFLite. Additionally, there are often cases where operations used in PyTorch are not supported in TFLite, resulting in frequent errors during the conversion process.</p>
<p>I appreciate it. Thank you!!!🔥🔥🔥</p> |
Google AI Open Images - Object Detection Track | 15th place solution [0.45 private LB] | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google AI Open Images - Object Detection Track
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I used single GPU for training. You can try multi GPU by uncommenting lines:</p>
<pre><code># '--multi-gpu', '2',
# '--multi-gpu-force',
</code></pre>
<p>You can remove these lines if they cause some trouble:</p>
<pre><code> print('Learning rate: {}'.format(K.get_value(model.optimizer.lr)))
# K.set_value(model.optimizer.lr, 1e-5)
print('Learning rate: {}'.format(K.get_value(model.optimizer.lr)))
</code></pre>
<p>I put the TensorFlow code in the same repo. You can find details here:</p>
<p><a href="https://github.com/ZFTurbo/Keras-RetinaNet-for-Open-Images-Challenge-2018/tree/master/tf_solution">https://github.com/ZFTurbo/Keras-RetinaNet-for-Open-Images-Challenge-2018/tree/master/tf_solution</a></p>
<p>Some contestants tell me that there is possbility to lower threshold for this pretrained model (graph reexport?) and it will start to generate more boxes with lower confidence score. This leads to much higher mAP. One contestant reports 0.37872 public LB, 0.34736 private LB without any changes in model. But I didn't check it.</p>
<p>Code already available:
<a href="https://github.com/ZFTurbo/Keras-RetinaNet-for-Open-Images-Challenge-2018">https://github.com/ZFTurbo/Keras-RetinaNet-for-Open-Images-Challenge-2018</a></p>
<p>There are inference and training examples.</p>
<h1>Software</h1>
<p>Windows 10 + Python 3.5 + Keras 2.2 + Keras-RetinaNet [0.4.1]: <a href="https://github.com/fizyr/keras-retinanet">https://github.com/fizyr/keras-retinanet</a></p>
<h1>Main approach</h1>
<p>All classes were split on 5 levels depends on children level. As the basis I used official classes hierarchy: <a href="https://storage.googleapis.com/openimages/challenge_2018/bbox_labels_500_hierarchy_visualizer/circle.html">https://storage.googleapis.com/openimages/challenge_2018/bbox_labels_500_hierarchy_visualizer/circle.html</a></p>
<ul>
<li><strong>Level 1</strong>: 443 classes - no children, have maximum impact on score</li>
<li><strong>Level 2</strong>: 46 classes - have children only with level 1</li>
<li><strong>Level 3</strong>: 4 classes: 'Seafood', 'Watercraft', 'Insect', 'Carnivore'</li>
<li><strong>Level 4</strong>: 4 classes: 'Vegetable', 'Land vehicle', 'Reptile', 'Invertebrate'</li>
<li><strong>Level 5</strong>: 3 classes: 'Furniture', 'Vehicle', 'Animal'</li>
</ul>
<p><strong>Note 1</strong>: It’s possible to split classes on 3rd, 4th and 5th levels differently. Only “Animal” class has real 5th level.</p>
<p><strong>Note 2</strong>: 3rd, 4th and 5th don’t have large impact on final score so I didn’t really tune these models.</p>
<p><strong>Note 3</strong>: Models of 2-5 levels optional, since we can generate predictions for them using Level 1 model. We just need to duplicate boxes for their children and use some NMS algo on them since there will appear some duplicates. Score for this approach will be slightly lower than using separate 2-5 level models (as I remember correctly ~0.01-0.02 lower).</p>
<h1>Why we need the split? Why we don’t train using all 500 classes?</h1>
<p>In process of dataset analysis I found out that there are some images which marked up only on higher level classes. The most explicit representatives are the Person class (2nd level) and Man, Woman, Boy, Girl (1st level). What's the problem? Images marked with the Person class do not have markup for Man, Woman, Boy and Girl. If we use these images for training at once for all classes - the model will be confused in the classes Man, Woman, Boy and Girl. You can throw out images for Person, but then it makes no sense to train this class as part of the overall model, but it's easier to generate markup for Person in the inference step (using boxes for Man, Woman, Boy and Girl).</p>
<p>To train 2-5 levels models, we can use more data, including images marked for example by Person besides images including subclasses (Man, Woman, Boy and Girl) and this improves the result.</p>
<h1>Preparing data for training</h1>
<p><strong>Level 1</strong>: All images containing markup for one of the 443 classes were added + images were added that contained the markup of the first-level classes not included in Challenge 500, as negative samples. Excluded all images containing markup of the higher levels in order to reduce the number of potential False negative (that is, the markup should be, but it is not in the training set).</p>
<p><strong>Levels 2 - 5</strong>: Images for each class contain both markups directly for this class, and for all children classes. Excluded images containing the higher level classes. Added images containing disjoint classes as negative samples.</p>
<p>Validation is rather slow on RetinaNet. I did a separate validation for the training process, where for each class there were about 25 images containing this class. Thus, I balanced the classes a bit and reduced the time of the validation. My validation during training was about 6.5K images instead of 41K.</p>
<h1>Best models</h1>
<pre><code>1) Keras RetinaNet + ResNet152 Image size ranges 600-800 px
mAP on small validation: 0.5028
mAP on full validation: 0.384009
LB score*: 0.47441
2) Keras RetinaNet + ResNet101 Image size ranges 768-1024 px
mAP on small validation: 0.4896
mAP on full validation: 0.377631
LB score*: 0.47549
</code></pre>
<ul>
<li><ul><li>I have not tried individual submissions by levels, just sent a merged result for the best models for all levels.</li></ul></li>
</ul>
<p><img src="https://storage.googleapis.com/kaggle-forum-message-attachments/379163/10220/ResNet101-loss.png" alt="enter image description here"></p>
<p><img src="https://storage.googleapis.com/kaggle-forum-message-attachments/379163/10218/ResNet101-valid-mAP.png" alt="enter image description here"></p>
<p><img src="https://storage.googleapis.com/kaggle-forum-message-attachments/379163/10219/ResNet152-loss.png" alt="enter image description here"></p>
<p><img src="https://storage.googleapis.com/kaggle-forum-message-attachments/379163/10217/ResNet152-valid-mAP.png" alt="enter image description here"></p>
<p>Models continue improving when I stopped training them, so I think there is some room to increase score.</p>
<h1>Process of training and inference</h1>
<p>Keras-RetinaNet already has a implemented generator for training on Open Images Dataset (OID). But in the current form it is not very suitable. I made several changes to it:</p>
<ul>
<li>I added support for “empty” class - for images with negative samples that do not contain any boxes.</li>
<li>In the current generator there are no augmentations associated with the color, I added a random change in the intensity of the channels - this gave a good increase in validation score. And it feels like augmentation set in Keras-Retinanet is not enough for training a strong model.</li>
<li>Most important, selecting just random images for the batch will work poor at random. I replaced it with the following method:
<ul><li>before the start of training for each class (including "empty") we create a list of images that contains boxes for the class.</li>
<li>during the training, to add the next image to the batch, we first randomly select a class, then randomly select the image from the image list for the class. Thus, we achieve more or less uniform training by classes. Strictly speaking, the distribution is still not quite uniform because the images usually contain boxes for several classes at once.</li></ul></li>
<li>From small things: I increased values for augmentations transform-generator, especially scale. I changed the value of factor from 0.1 to 0.9 in ReduceLROnPlateau because the learning rate dropped too fast.</li>
<li>At the stage of the convert model for inference, in the FilterDetections layer in RetinaNet - reduced the score_threshold from 0.05 to 0.01 and tried to increase the number of boxes from 300 to 500. This gives more flexibility in the ensemble stage. Also note that the default model RetinaNet for Inference already contains NMS in the FilterDetections layer with nms_threshold = 0.5 and there is a feeling that you can play with this parameter.</li>
<li>I restarted training several times with a large LR = 1e-5, when LR fell too low. And each time the model became better. But the experiment is not very clean, because every time I changed the augmentation parameters.</li>
</ul>
<h1>Ensembles</h1>
<ul>
<li>For each model, I made a prediction on the image and its horizontal mirror.</li>
<li>RetinaNet has internal layer with made NMS on single image prediction (it can be switched off to get the full set of boxes, but I didn’t try it).</li>
<li>I merged boxes using two methods:
<ul><li>standard NMS (<a href="https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/nms.py"></a><a href="https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/nms.py">https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/nms.py</a>), the optimal threshold I found was about 0.75. </li>
<li>second method is my own heuristic. It works better on LB. Heuristics included a weighted addition of boxes, which changed their coordinates and Confidence score.</li></ul></li>
<li>I also tried Soft NMS [https://github.com/bharatsingh430/soft-nms] last 3 days of competition, but it works almost the same as default NMS and worse than my ensemble approach. Probably I missed something.</li>
</ul>
<h1>My ensemble approach in short</h1>
<ol>
<li>On input we get set of boxes from different N models</li>
<li>Set “Init_weight” = 1/N and initialize “result” set of boxes as empty list</li>
<li>Add all boxes for best model with “init_weight” weight to “result” list. For all other boxes of other models try to find best matching box in result using IOU. If box with IOU > THR (0.55) exists in “result” then merge best found box in result with it using weighted average for coordinates and confidence score. Increase weight of this box by Init_weight value. Otherwise add this new box to “result” with “init_weight” weight.</li>
</ol>
<h1>Other solutions</h1>
<p>At the first stage I tried to solve the problem simply on pretrain models without any retraining:</p>
<ul>
<li>RetinanNet Pretrain Coco: <a href="https://github.com/fizyr/keras-retinanet/releases">https://github.com/fizyr/keras-retinanet/releases</a> - gives an approximately 0.13 on LB, if the classes between OID and COCO are correctly matched.</li>
<li>On the pretrain from here: <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb">https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb</a> using this model: faster_rcnn_inception_resnet_v2_atrous_oid_2018_01_28 you can get ~0.25 on LB.</li>
</ul>
<h1>Observations and small tricks</h1>
<ol>
<li>Because of the metric nature, it is better to output the maximum number of rectangles even with low confidence score.</li>
<li>Validation works so-so. In most cases, it is worse than LB. Most likely this is due to two factors: the distribution in kaggle test is very different from the distribution for validation. Classes with a small number of elements affect the score as much as others.</li>
<li>The limitation on the size of the CSV file on Kaggle in this task is ~2GB. This fact didn't allow to submit more boxes with low confidence score.</li>
</ol>
<h1>Proposed dataset improvement</h1>
<p>In case we will have similar competitions next years:</p>
<ul>
<li>To simplify the task organizers should improve the training dataset, so that there are no situations when there is a markup for level 2 and there is no markup for level 1. </li>
<li>It would be good to have a full markup for each image with all the boxes including the parent classes. To avoid discrepancies / errors, etc.</li>
<li>It’s better to use actual class names like "Ambulance" instead of /m/012n7d</li>
<li>A little confusing is the presence of the flags like “isGroupOf” - are there any images of such type in the Test set or not? I eventually excluded these images from training and still not sure if it was right thing to do.</li>
<li>It seems to me that the current metric is not very good due to the fact that classes with a very small number of boxes influence just like classes with millions of boxes. Small mistakes can lead to significant score changes.</li>
</ul>
<h1>Code and PreTrained models</h1>
<p>GitHub repository: <a href="https://github.com/ZFTurbo/Keras-RetinaNet-for-Open-Images-Challenge-2018">https://github.com/ZFTurbo/Keras-RetinaNet-for-Open-Images-Challenge-2018</a></p>
<p>Thanks. ) I'm currently preparing code with my solution for github. I'm not sure if I will be able to directly make PR to keras-retinanet since there are some dependencies on my code and directory structure. But code for updated generator will be available in my repository.</p>
<p>I used NVIDIA GTX 1080 Ti</p>
<ul>
<li>Training with ResNet101 (img size 768-1024) one epoch 10000 images: ~6400 sec </li>
<li>Training with ResNet152 (img size 600-800) one epoch 10000 images: ~5200 sec</li>
</ul>
<p>Inference can't say exactly but something like 500 ms per image I guess.</p> |
Google AI Open Images - Object Detection Track | 17th place solution | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google AI Open Images - Object Detection Track
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congrats winners and all participants!</p>
<p>My solution is very simple.</p>
<p><strong>First-Stage</strong> Train ResNet50-FPN Faster RCNN model with all training data (480000 iters, 8 batches).
I trained this model to predict all 500 classes without descrimination of label's hierarchy.
ResNet50-FPN Faster RCNN code is (<a href="https://github.com/Hakuyume/chainer-fpn">https://github.com/Hakuyume/chainer-fpn</a>).</p>
<p><strong>Second-Stage</strong> Train this model with sampling training data. (230000 iters, 8 batches)
I down-sampled only the classes contained in many images(>= 5,000 images)
First-Stage, it took a long long time with my machine, so I tried training with this down-sampled data to train rare classes well.</p>
<p><strong>Third-Stage</strong> Predict test images (normal and horizontal flip).
I added expand labels to predict result based on label's hierarchy.
e.g.</p>
<p>label, score, xmin, xmax, ymin, ymax</p>
<p>FootBall Helmet, 0.5, 0.1, 0.3, 0,2, 0.4</p>
<p>-></p>
<p>FootBall Helmet, 0.5, 0.1, 0.3, 0,2, 0.4</p>
<p>Helmet, 0.5, 0.1, 0.3, 0.2, 0.4</p>
<p><a href="https://storage.googleapis.com/openimages/web/object_detection_metric.html">https://storage.googleapis.com/openimages/web/object_detection_metric.html</a></p>
<p><strong>Fourth-Stage</strong> combine expanded predicts (normal and horizontal filp) with non-maximum supressions. </p> |
Google AI Open Images - Object Detection Track | 19th place solution overview [and trained weights] | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google AI Open Images - Object Detection Track
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I have not tried running the webcam demo, quite surprised 8GB is not enough. I performed inference on a 1080TI which has 11GB of RAM.</p>
<p>I pushed some changes to the config - not sure if this will help but worth a try.</p>
<p>I trained <a href="https://pjreddie.com/darknet/yolo/">yolov3</a> with SPP using <a href="https://pjreddie.com/media/files/darknet53.conv.74">darknet53.conv.74</a> weights pretrained on Imagenet.</p>
<p>I followed the training regime and used the same architecture that the creators of yolo used for training on COCO. Most likely better results could be achieved on the Open Images dataset should the capacity of the model be increased.</p>
<p>I emulated the conditions of training on COCO and created two custom datasets. I initially (up to ~ 250k batches IIRC) trained on ~320k files, increasing the dataset to ~430k files onwards. I picked the files to train on to ensure as balanced a representation of each class as possible (picked all images that contained rare labels - limited number of images to include for more popular labels to arrive at the target file count).</p>
<p>I trained the model thx to the GCP coupon using a preemptible instance / premptible GPUs. I went with 16 vCPUs and 4 preemptible P100s. I didn't measure this precisely but I think in 24 hrs the model trained on ~50k batches, maybe a bit more. The full training schedule is just over 500k batches.</p>
<p>I believe that appropriate makeup of the trainset is key to achieving a good result. This is an observation that I have not verified though.</p>
<p>I have not modified the train set labels in any way. I also don't believe I have expanded the labels before training to include parent categories but might be wrong on that one. Doing something reasonable with the label hierarchy should grant further improvement in performance.</p>
<p>My private LB score is slightly different as I tried training on a subset of labels / files for trainingtrain set selected in a specific way to help me in the VRD track but I didn't get very far (partially due to this likely being the wrong approach and partially due to running out of time).</p>
<p>I am sharing the final weights and the config files in this github <a href="https://github.com/radekosmulski/yolo_open_images">repository</a>.</p>
<p>Here is the citation of the paper that introduces yolov3:</p>
<p>> @article{yolov3, title={YOLOv3: An Incremental Improvement}, <br>
> author={Redmon, Joseph and Farhadi, Ali}, journal = {arXiv}, <br>
> year={2018} }</p>
<p>And <a href="https://arxiv.org/abs/1804.02767">here</a> is where you can find the paper on arxiv.</p>
<p>Thank you! Darknet does the rescaling on the fly for you to a couple of different resolutions to train on objects of various sizes. I trained with a max size of 608x608.</p>
<p>The data I downloaded and used for training came from a storage bucket whose address I believe I have found on github in the object detection API repository, though might have been somewhere else. I don't recall now (and don't have access to my rig at the moment) but I believe the images were rescaled to either 1024 for the longer edge or were slightly bigger.</p>
<p>Could you please try pulling the repository from <a href="https://bitbucket.org/dreamwalkerrr/yolo_open_images">bitbucket</a>? I think this should work</p> |
Google AI Open Images - Object Detection Track | 26th place solution [0.38 private LB] | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google AI Open Images - Object Detection Track
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Software</h1>
<ul>
<li>Ubuntu 16.04</li>
<li>tensorflow</li>
<li>yolo3: <a href="https://github.com/qqwweee/keras-yolo3">https://github.com/qqwweee/keras-yolo3</a></li>
<li>faster rcnn: object detection in official models of tensorflow models</li>
</ul>
<h1>Main approach</h1>
<ul>
<li>data balancing</li>
<li>tricks of learning rate</li>
<li>study the rule of scoring</li>
</ul>
<h1>Code</h1>
<ul>
<li><a href="https://github.com/rabienrose/GoogleAIOpenImg2018">https://github.com/rabienrose/GoogleAIOpenImg2018</a></li>
<li>Include the necessary files for my project from tensorflow models and keras-yolo3</li>
</ul>
<h1>Experience</h1>
<ul>
<li>One of my friends suddenly asked me to join the challenge one day. I have never involved in any this kind of competition and I have not done any object detection projects before. I only did some classification projects before.Just reading the rule for the competition make me uneasy. But, I like the feeling of pushing myself to the limit, so I started to download the tensorflow models for github.</li>
<li>I first tried the fast-rcnn model, before it was said the most powerful model current. But it was too slow to train, about 600ms per image with my 1080ti. I only trained with about 20,000 images for couple of epoch. The first submission is very bad, only something like 0.00002. The main result not because the training is bad but because some bugs: I mistake the order of xmin, ymin and so on. After fixed this, I got score like 0.02.</li>
<li>The speed of training is a problem, with that speed, I have no time to adjust the model and study the result. So, I decided to move to yolo3. And I also do some data balancing: get rid of images that only contain the very common objects like person, face. Finally, I chose 200,000 images out of 1700,000 train images.</li>
<li>It was about 4 hours to train one epoch, I increase the learning rate a little bit if I find the loss enters the platform status. Otherwise I just linearly decrease the learning rate as epoch increase.</li>
</ul>
<h1>Other configs</h1>
<ul>
<li>Confidence threshold: 0.01</li>
<li>Expand the classes based on the hierarchy after prediction, not before training</li>
<li>No ensemble (I really did not have time to train multiple models)</li>
</ul>
<p>the way of calculating AP require you to submit all the result, both true and false class. The reason why it is 0.01 not 0, is because the evaluation system have the size limit of uploading file.</p> |
Google AI Open Images - Object Detection Track | 2nd place solution [0.58 private LB] | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google AI Open Images - Object Detection Track
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks for the request. We are currently discussing this internally whether to make it public later on.</p>
<p>Thanks for your question. We use co-occurrence loss only for the head network. E.g. if 'person' is annotated, but the network predicts 'human face' within the area of the 'person' ground-truth, we ignore the prediction when calculating the loss.</p>
<p>Well, we just got a brand-new cluster, and thought we'd take it out for a spin. ;)
<a href="https://www.preferred-networks.jp/en/news/pr20180328">https://www.preferred-networks.jp/en/news/pr20180328</a></p>
<p>P.S. We're hiring: <a href="https://www.preferred-networks.jp/en/jobs">https://www.preferred-networks.jp/en/jobs</a></p>
<p>We simply call NMW instead of NMS to suppress duplicate detections. You can think of it as an extension of NMS that uses a weighted average for voting for the position of the final bounding box. NMW is not our idea, but it was proposed in the following ICCV 2017 workshop paper: <a href="http://openaccess.thecvf.com/content_ICCV_2017_workshops/papers/w14/Zhou_CAD_Scale_Invariant_ICCV_2017_paper.pdf">http://openaccess.thecvf.com/content_ICCV_2017_workshops/papers/w14/Zhou_CAD_Scale_Invariant_ICCV_2017_paper.pdf</a>
Please see Section 3.4 for details of how it works.</p>
<p>Thanks for the interesting paper!
With NMW, we got around 0.65 mAP improvement back when we got around 47- 48 mAP on the public LB, but I'm afraid I don't have any more recent ablative results at the moment.</p>
<p><a href="https://arxiv.org/abs/1809.00778">https://arxiv.org/abs/1809.00778</a></p>
<p>Here is our technical report for team PFDet's 2nd place solution.</p>
<p>P.S. We're hiring: <a href="https://www.preferred-networks.jp/en/jobs">https://www.preferred-networks.jp/en/jobs</a></p> |
Google AI Open Images - Object Detection Track | 86th place solution, with full source code of keras-yolo3 | Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge | <|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Google AI Open Images - Object Detection Track
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This is the first Kaggle competition I formally participated in. I used a Keras implementation of YOLOv3 on the problem. Limited by time and GPU resources, I did not do particularly well in the end. My final private leaderboard score is only 0.16889 (86th place).</p>
<p>Anyway, I wrote a blog post about what I've learned from this competition. And I'm willing to share all source code I used to work on the problem. That includes:</p>
<ul>
<li>code to convert Open Images dataset annotations to YOLOv3 format.</li>
<li>use of LRFinder to find better learning rate ranges for training the model.</li>
<li>use of Cyclic Learning Rate (CLR) scheduler.</li>
<li>use of SGDAccum to accumulate gradients over multiple batches (which is not formally supported by Keras). </li>
<li>code to test, visualize and verify the trained YOLOv3 model.</li>
<li>code to generate the csv files for Kaggle submission.</li>
</ul>
<p>Hopefully, the code could benefit other people who are new to Kaggle competitions. You could find links to my blog post and GitHub repo below.</p>
<p><a href="https://jkjung-avt.github.io/kaggle-open-images/">Kaggle 2018 Google AI Open Images - Object Detection Track</a></p>
<p><a href="https://github.com/jkjung-avt/keras-yolo3">jkjung-avt/keras-yolo3</a></p> |
Subsets and Splits