{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.12.13"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":154281,"sourceType":"competition"},{"sourceId":251736,"sourceType":"datasetVersion"},{"sourceId":18673450,"sourceType":"datasetVersion"},{"sourceId":18673646,"sourceType":"datasetVersion"},{"sourceId":18706996,"sourceType":"datasetVersion"},{"sourceId":18716507,"sourceType":"datasetVersion"},{"sourceId":341776840,"sourceType":"kernelVersion"},{"sourceId":4533,"sourceType":"modelInstanceVersion"}],"isGpuEnabled":false,"isInternetEnabled":true,"language":"python","sourceType":"notebook"},"papermill":{"default_parameters":{},"duration":197.997222,"end_time":"2026-08-11T20:39:00.353517+00:00","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2026-08-11T20:35:42.356295+00:00","version":"2.7.0"},"widgets":{"application/vnd.jupyter.widget-state+json":{"state":{"008a4142bff44c71918143d71fe8d218":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"01bf2df8a2bf43f8a03d8021e89119c6":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_855463d8055941cb9d5ed1163f95132e","IPY_MODEL_a2d86ebf9efc458295703c08e2c1dbf2","IPY_MODEL_5afebaefc62348c7b5a69b666b0e59bb"],"layout":"IPY_MODEL_0d576a2521ff4587a6c8b0fff83f4546","tabbable":null,"tooltip":null}},"0b831a653eea42458aaa43e25326d5b1":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_6249ebd6553b4a3aae03df2c11dcaf08","placeholder":"​","style":"IPY_MODEL_9fe9639d0cf74c5ab03245fdd8765386","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"0d576a2521ff4587a6c8b0fff83f4546":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"1eb5af85fdcd4bc5887e07351ed490ea":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"22d3c052d4fe44c685a7a5b8d6f48a41":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_4bc7670e3a7f4d55a17cdec0b0c4ef82","IPY_MODEL_73b4d452a1c441aebaed5ff33a2fb286","IPY_MODEL_b23749b32e8d4c0f984d8a6d9faa1e43"],"layout":"IPY_MODEL_f7b7452d7376411d8a7d423a3b0d416b","tabbable":null,"tooltip":null}},"23c78d5db3b1464880bbc5215c810c4d":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"2899ec71045c457f8e8002e1f890fc7d":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"3201d69c25114a5aa816c82aa80ca8bb":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"3487434fada54ef98ef9eeda91b117b6":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"3c088a73a35945449d0ae592d82a39a2":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"40cabeb934b34fcea9af5478335fc903":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"41636f2742544804991ae2eb16504787":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"446ae3a954aa450399e323d11658b57e":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_cc534ebe95f444a5847c02a9917ad6db","placeholder":"​","style":"IPY_MODEL_3487434fada54ef98ef9eeda91b117b6","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"470b7bed4bce4f6cbe23554ca0abd2a1":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"4bc7670e3a7f4d55a17cdec0b0c4ef82":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_7b7d414621f14734aa9df46f326c2134","placeholder":"​","style":"IPY_MODEL_470b7bed4bce4f6cbe23554ca0abd2a1","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"4ec7d5b6d8a04b4fa3434df3a41fa7cb":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_0b831a653eea42458aaa43e25326d5b1","IPY_MODEL_fda61acedc974c05906725c46a3005c3","IPY_MODEL_520ba025b24248fba81608b9a9d62b6f"],"layout":"IPY_MODEL_57c42efff0914a0e877be4875bd936d5","tabbable":null,"tooltip":null}},"520ba025b24248fba81608b9a9d62b6f":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_008a4142bff44c71918143d71fe8d218","placeholder":"​","style":"IPY_MODEL_b57530b3dba74f9896ba71febfbd80c1","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 928.48it/s, Materializing param=layernorm.weight]"}},"53cc6cc58489415b9de1d472b76a8b44":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"57c42efff0914a0e877be4875bd936d5":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"5afebaefc62348c7b5a69b666b0e59bb":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_9e2e5db2909b447daf815269adf3268f","placeholder":"​","style":"IPY_MODEL_a2abe0ac24ed40c0939ee34b66a35d57","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 954.51it/s, Materializing param=layernorm.weight]"}},"5fb4cb399b504658afb569d241e8db40":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_f4900ef12a614b7c8725a3835f929e57","placeholder":"​","style":"IPY_MODEL_2899ec71045c457f8e8002e1f890fc7d","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"6162c16a95954fdd82ebb3d7c4e16f94":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_446ae3a954aa450399e323d11658b57e","IPY_MODEL_b3565035dd934f50bec336b117522634","IPY_MODEL_785f44768b5943d3b0fbdff5cd248324"],"layout":"IPY_MODEL_d634dc74602f4f48bd6274e362aa2cc4","tabbable":null,"tooltip":null}},"6249ebd6553b4a3aae03df2c11dcaf08":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"6b1270dda04a48aaa40db23c2d6c96d7":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"6e4ce666d9264448a73669c171de4fdf":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"73b4d452a1c441aebaed5ff33a2fb286":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"ProgressView","bar_style":"success","description":"","description_allow_html":false,"layout":"IPY_MODEL_964af8918b494d3a9fd28cd5156cb7eb","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_7ab8c976d74e4a9895cebada0dcb3138","tabbable":null,"tooltip":null,"value":223}},"785f44768b5943d3b0fbdff5cd248324":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_1eb5af85fdcd4bc5887e07351ed490ea","placeholder":"​","style":"IPY_MODEL_23c78d5db3b1464880bbc5215c810c4d","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 877.23it/s, Materializing param=layernorm.weight]"}},"7ab8c976d74e4a9895cebada0dcb3138":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"7b7d414621f14734aa9df46f326c2134":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"82b32f1716f14cbba4b6fd3c52386175":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"855463d8055941cb9d5ed1163f95132e":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_b2c2bf961f3a42b6a9eabc328931bb35","placeholder":"​","style":"IPY_MODEL_6b1270dda04a48aaa40db23c2d6c96d7","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"964af8918b494d3a9fd28cd5156cb7eb":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"9e2e5db2909b447daf815269adf3268f":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"9fe9639d0cf74c5ab03245fdd8765386":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"a2abe0ac24ed40c0939ee34b66a35d57":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"a2d86ebf9efc458295703c08e2c1dbf2":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"ProgressView","bar_style":"success","description":"","description_allow_html":false,"layout":"IPY_MODEL_41636f2742544804991ae2eb16504787","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_3c088a73a35945449d0ae592d82a39a2","tabbable":null,"tooltip":null,"value":223}},"a448a192c5bc428e8b49629ce50feb5f":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"ProgressView","bar_style":"success","description":"","description_allow_html":false,"layout":"IPY_MODEL_82b32f1716f14cbba4b6fd3c52386175","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_40cabeb934b34fcea9af5478335fc903","tabbable":null,"tooltip":null,"value":223}},"a924058817c34c518d80003fc10941c8":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"af412279449a46cabedf375a7423fd7f":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"b0bb425a0e4543b598e57aeac56294b2":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"b23749b32e8d4c0f984d8a6d9faa1e43":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_b0bb425a0e4543b598e57aeac56294b2","placeholder":"​","style":"IPY_MODEL_d5f97ac9bb0a4bffbd9af996c32253cc","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 925.79it/s, Materializing param=layernorm.weight]"}},"b2c2bf961f3a42b6a9eabc328931bb35":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"b3565035dd934f50bec336b117522634":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"ProgressView","bar_style":"success","description":"","description_allow_html":false,"layout":"IPY_MODEL_a924058817c34c518d80003fc10941c8","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_af412279449a46cabedf375a7423fd7f","tabbable":null,"tooltip":null,"value":223}},"b57530b3dba74f9896ba71febfbd80c1":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"c7ab8c0823d845fe9be4bfd43d72edfa":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_cd83f48335ad4768b8596fab4c10d50e","placeholder":"​","style":"IPY_MODEL_3201d69c25114a5aa816c82aa80ca8bb","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 1006.72it/s, Materializing param=layernorm.weight]"}},"cc534ebe95f444a5847c02a9917ad6db":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"cc9bf0ec2246442f9e77ecb2eec72658":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_5fb4cb399b504658afb569d241e8db40","IPY_MODEL_a448a192c5bc428e8b49629ce50feb5f","IPY_MODEL_c7ab8c0823d845fe9be4bfd43d72edfa"],"layout":"IPY_MODEL_6e4ce666d9264448a73669c171de4fdf","tabbable":null,"tooltip":null}},"cd83f48335ad4768b8596fab4c10d50e":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"d5f97ac9bb0a4bffbd9af996c32253cc":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"d634dc74602f4f48bd6274e362aa2cc4":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"f4900ef12a614b7c8725a3835f929e57":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"f7b7452d7376411d8a7d423a3b0d416b":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"fcd6dd287a084871a314bb9107cf1b11":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"fda61acedc974c05906725c46a3005c3":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"ProgressView","bar_style":"success","description":"","description_allow_html":false,"layout":"IPY_MODEL_fcd6dd287a084871a314bb9107cf1b11","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_53cc6cc58489415b9de1d472b76a8b44","tabbable":null,"tooltip":null,"value":223}}},"version_major":2,"version_minor":0}}},"nbformat_minor":4,"nbformat":4,"cells":[{"id":"195757f2","cell_type":"markdown","source":"# RSNA Knee — Notebook 04: Target-Specialist Fine-Tuning (FT-C)\n\nThis stage is deliberately **more conservative than FT-A and FT-B**.\n\nNotebook 03 showed:\n\n- BASE expert-CV macro AUC ≈ **0.97897**\n- FT-A macro AUC ≈ **0.97237**\n- FT-B macro AUC ≈ **0.97204**\n- FT-B improved calibration/BCE, but did not beat BASE in overall ranking.\n- FT-B did improve several structural targets relative to FT-A.\n\nTherefore FT-C does **not** continue moving the whole backbone. It creates a true\nstructural specialist for:\n\n- ACL\n- MCL\n- Medial Meniscus\n- Lateral Meniscus\n\nOnly the target-specific `query` and `out` rows receive gradient from those four targets.\nThe DINO backbone, LayerNorm, shared projection and slot embeddings are frozen.\n\nEach fold starts from its Stage-3 FT-B checkpoint. If the specialist gate does not\nimprove the fold-local specialist objective, the output is an exact rollback to FT-B.\n\n**No `submission.csv` is created here.** Notebook 05 will perform final OOF branch/blend\nselection, test inference and write exactly `/kaggle/working/submission.csv`.","metadata":{}},{"id":"a9af6d5a","cell_type":"markdown","source":"## Fixed V2 — corrected after full traceback review\n\nThis version fixes the failed Stage-4 run:\n\n1. `STAGE2` → `STAGE3` in checkpoint discovery.\n2. Prevents the resulting empty `pixel_groups/group_cache` cascade.\n3. Makes `build_model(0)` correctly freeze **all** DINO blocks.\n4. Makes the specialist update truly isolated to ACL/MCL/meniscus target rows:\n   zero AdamW decay plus explicit restoration of all 8 non-specialist rows.\n5. Adds non-specialist prediction-drift checks.\n6. Blocks the summary cell if training did not complete, instead of producing\n   secondary `metrics is not defined` errors.\n\nUse the same inputs as before: competition data + DINOv2-small + Notebook 03 output.","metadata":{}},{"id":"b55e33fb","cell_type":"code","source":"from __future__ import annotations\n\nimport os\nfor _v in (\"OMP_NUM_THREADS\", \"OPENBLAS_NUM_THREADS\", \"MKL_NUM_THREADS\"):\n    os.environ.setdefault(_v, \"4\")\n\nimport gc\nimport json\nimport math\nimport re\nimport shutil\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport pydicom\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom IPython.display import display\nfrom sklearn.metrics import roc_auc_score\n\nT0 = time.time()\nSEED = int(os.environ.get(\"FTC_SEED\", \"27182\"))\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\nif torch.cuda.is_available():\n    torch.cuda.manual_seed_all(SEED)\n\nTARGETS = [\n    \"ACL\", \"MCL\", \"Medial Meniscus\", \"Lateral Meniscus\", \"Medial OA\",\n    \"Lateral OA\", \"PF OA\", \"Effusion\", \"Synovitis\", \"Baker's\",\n    \"Contusion\", \"Fracture\",\n]\n\n# Pre-declared anatomy-driven specialist. This is not chosen by peeking at one\n# validation fold during training.\nSPECIALIST_TARGETS = [\n    \"ACL\", \"MCL\", \"Medial Meniscus\", \"Lateral Meniscus\",\n]\nSPECIALIST_IDX = np.asarray([TARGETS.index(t) for t in SPECIALIST_TARGETS], dtype=int)\n\nFTC_MAX_EPOCHS = int(os.environ.get(\"FTC_MAX_EPOCHS\", \"4\"))\nFTC_PATIENCE = int(os.environ.get(\"FTC_PATIENCE\", \"2\"))\nFTC_HEAD_LR = float(os.environ.get(\"FTC_HEAD_LR\", \"1e-4\"))\nFTC_WEIGHT_DECAY = float(os.environ.get(\"FTC_WEIGHT_DECAY\", \"0.005\"))\nFTC_BATCH = int(os.environ.get(\"FTC_BATCH\", \"2\"))\nFTC_GRAD_ACCUM = int(os.environ.get(\"FTC_GRAD_ACCUM\", \"2\"))\n\n# Promotion gate.\nFTC_MIN_SPEC_AUC_GAIN = float(os.environ.get(\"FTC_MIN_SPEC_AUC_GAIN\", \"0.001\"))\nFTC_SPEC_AUC_TIE = float(os.environ.get(\"FTC_SPEC_AUC_TIE\", \"0.001\"))\nFTC_SPEC_BCE_GAIN = float(os.environ.get(\"FTC_SPEC_BCE_GAIN\", \"0.002\"))\nFTC_MAX_SPEC_BCE_WORSEN = float(os.environ.get(\"FTC_MAX_SPEC_BCE_WORSEN\", \"0.015\"))\nFTC_MAX_FULL_AUC_DROP = float(os.environ.get(\"FTC_MAX_FULL_AUC_DROP\", \"0.006\"))\n\nEVAL_BATCH = int(os.environ.get(\"FTC_EVAL_BATCH\", \"4\"))\nTIME_BUDGET = float(os.environ.get(\"FTC_TIME_BUDGET_HOURS\", \"8\")) * 3600\n\nCROP_MM = 130.0\nCACHE_IMG = 336\nIMG = CACHE_IMG\nGROUP = 3\nCACHE_SLICES = 12\nN_GROUP = max(CACHE_SLICES // GROUP, 1)\nSLICE_BAND = (0.20, 0.80)\n\nHDR_THREADS = int(os.environ.get(\"HDR_THREADS\", \"16\"))\nPIX_THREADS = int(os.environ.get(\"PIX_THREADS\", \"12\"))\nORDER_THREADS = int(os.environ.get(\"ORDER_THREADS\", \"32\"))\nORDER_BUDGET_S = 5400\nLAT_MIN_OFFSET_MM = 20.0\nLEGACY_LAT_OFFSET_MM = 5.0\n\nRULES_NATIVE = {\n    \"order\": \"normal\",\n    \"lat\": \"centre\",\n    \"slot_fallback\": False,\n    \"decode_fill\": \"nearest\",\n}\nRULES_LEGACY = {\n    \"order\": \"dominant_axis\",\n    \"lat\": \"corner_x\",\n    \"slot_fallback\": True,\n    \"decode_fill\": \"zero\",\n}\nRULES = dict(RULES_NATIVE)\n\nSLOTS_RECOVERED = [\n    (\"SAG_FLUID_FS\", \"Sagittal\", True, True),\n    (\"COR_FLUID_FS\", \"Coronal\", True, True),\n    (\"AX_FLUID_FS\", \"Axial\", True, True),\n    (\"SAG_FLUID_NOFS\", \"Sagittal\", True, False),\n    (\"COR_T1\", \"Coronal\", False, False),\n    (\"SAG_T1\", \"Sagittal\", False, False),\n]\nSLOTS_PUBLIC = [\n    (\"SAG_FLUID\", \"Sagittal\", None, True),\n    (\"COR_FLUID\", \"Coronal\", None, True),\n    (\"AX_FLUID\", \"Axial\", None, True),\n    (\"SAG_STRUCT\", \"Sagittal\", None, False),\n    (\"COR_STRUCT\", \"Coronal\", None, False),\n    (\"AX_STRUCT\", \"Axial\", None, False),\n]\nSLOTS = SLOTS_RECOVERED\nN_SLOT = len(SLOTS)\n\nPOOL_PARTS = {\"cls_mean\": 2, \"cls_mean_focal\": 3}\nSLOT_PRIOR_TABLE = {\n    \"ACL\": (0, 3, 5), \"MCL\": (1, 4),\n    \"Medial Meniscus\": (0, 1, 3, 4), \"Lateral Meniscus\": (0, 1, 3, 4),\n    \"Medial OA\": (1, 4, 5), \"Lateral OA\": (1, 4, 5),\n    \"PF OA\": (0, 2, 5), \"Effusion\": (0, 2), \"Synovitis\": (0, 2),\n    \"Baker's\": (0,), \"Contusion\": (0, 1, 2), \"Fracture\": (0, 1, 2, 4, 5),\n}\nSLOT_PRIOR_STRENGTH = 0.55\n\nFATSAT_OPTS = {\"FS\", \"FATSAT\", \"FAT_SAT\", \"FSAT\"}\n_SEP = re.compile(r\"[_\\-.]\")\n_FATSAT_RX = re.compile(\n    r\"\\bfs\\b|fatsat|fat sat|\\bstir\\b|\\bspair\\b|\\bspir\\b|\\bwe\\b|\"\n    r\"water excit|\\btirm\\b|\\bsting\\b|\\bfatsup\\b\"\n)\n_T1_RX = re.compile(r\"\\bt1\\b|\\bt1w\\b\")\n_T2_RX = re.compile(r\"\\bt2\\b|\\bt2w\\b\")\n_PD_RX = re.compile(r\"\\bpd\\b|\\bpdw\\b|proton|\\bdp\\b|dens\")\n\nFRONTIER_TARGET_POOL = {\n    \"Fracture\": \"max\",\n    \"Contusion\": \"max\",\n    \"Medial Meniscus\": \"max\",\n    \"Lateral Meniscus\": \"max\",\n    \"ACL\": \"top2\",\n    \"MCL\": \"top2\",\n    \"Baker's\": \"max\",\n}\n\nOUT = Path(\"/kaggle/working/rsna_stage4_ftc\")\nOUT.mkdir(parents=True, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:21.665755Z","iopub.execute_input":"2026-08-11T20:59:21.666451Z","iopub.status.idle":"2026-08-11T20:59:21.68451Z","shell.execute_reply.started":"2026-08-11T20:59:21.666421Z","shell.execute_reply":"2026-08-11T20:59:21.68354Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"9a6e7356","cell_type":"code","source":"def log(msg):\n    print(f\"[{time.time() - T0:7.1f}s] {msg}\", flush=True)\n\n\nclass WeightsError(RuntimeError):\n    pass\n\n\ndef find_train_root():\n    explicit = os.environ.get(\"KNEE_INPUT_DIR\", \"\").strip()\n    candidates = [Path(explicit)] if explicit else []\n    candidates += [\n        Path(\"/kaggle/input/competitions/rsna-knee-abnormality-detection\"),\n        Path(\"/kaggle/input/rsna-knee-abnormality-detection\"),\n    ]\n\n    for c in candidates:\n        if (c / \"train.csv\").is_file() and (c / \"train_series\").is_dir():\n            return c\n\n    base = Path(\"/kaggle/input\")\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            root = Path(root)\n            if (root / \"train.csv\").is_file() and (root / \"train_series\").is_dir():\n                return root\n\n    raise FileNotFoundError(\"RSNA Knee competition training mount not found\")\n\n\ndef _looks_like_dinov2_config(config_path: Path):\n    try:\n        cfg = json.loads(config_path.read_text())\n    except Exception:\n        return False\n    text = json.dumps(cfg).lower()\n    return (\n        cfg.get(\"model_type\", \"\").lower() == \"dinov2\"\n        or \"dinov2\" in text\n        or any(\"dinov2\" in str(x).lower() for x in cfg.get(\"architectures\", []) or [])\n    )\n\n\ndef find_dinov2(variant=\"small\"):\n    explicit = os.environ.get(\"KNEE_DINOV2_DIR\", \"\").strip()\n    if explicit:\n        p = Path(explicit)\n        if (p / \"config.json\").is_file():\n            return p\n        raise FileNotFoundError(f\"KNEE_DINOV2_DIR={explicit!r} has no config.json\")\n\n    preferred = Path(\"/kaggle/input/models/metaresearch/dinov2/pytorch/small/1\")\n    if str(variant).lower() == \"small\" and (preferred / \"config.json\").is_file():\n        return preferred\n\n    base = Path(\"/kaggle/input\")\n    strong, weak = [], []\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            if \"config.json\" not in files:\n                continue\n            p = Path(root)\n            if _looks_like_dinov2_config(p / \"config.json\"):\n                strong.append(p)\n            elif \"dinov2\" in str(p).lower():\n                weak.append(p)\n\n    hits = strong or weak\n    if not hits:\n        return None\n\n    target_hidden = {\"small\": 384, \"base\": 768, \"large\": 1024, \"giant\": 1536}.get(\n        str(variant).lower()\n    )\n    if target_hidden is not None:\n        for p in hits:\n            try:\n                cfg = json.loads((p / \"config.json\").read_text())\n                if int(cfg.get(\"hidden_size\", -1)) == target_hidden:\n                    return p\n            except Exception:\n                pass\n    return hits[0]\n\n\ndef _is_stage3_dir(p: Path):\n    required = [\n        \"stage3_status.json\",\n        \"manifest.json\",\n        \"expert_cv_predictions_stage3.csv\",\n        \"expert_cv_target_auc_stage3.csv\",\n        \"expert_cv_branch_summary.csv\",\n    ]\n    return all((p / x).is_file() for x in required)\n\n\ndef find_stage3():\n    explicit = os.environ.get(\"STAGE3_DIR\", \"\").strip()\n    if explicit:\n        p = Path(explicit)\n        if _is_stage3_dir(p):\n            return p\n        raise FileNotFoundError(f\"STAGE3_DIR={explicit!r} is not a complete Stage 3 output\")\n\n    base = Path(\"/kaggle/input\")\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            p = Path(root)\n            if not _is_stage3_dir(p):\n                continue\n            try:\n                st = json.loads((p / \"stage3_status.json\").read_text())\n            except Exception:\n                continue\n            if st.get(\"stage\") == \"FT-B_HARD_EXAMPLE\" and st.get(\"stage3_ok\"):\n                return p\n\n    raise FileNotFoundError(\n        \"Notebook 03 output not found. Add Notebook 03 output as a Kaggle input \"\n        \"or set STAGE3_DIR.\"\n    )\n\n\nROOT = find_train_root()\nSTAGE3 = find_stage3()\nDINO = find_dinov2(\"small\")\n\nlog(f\"competition root: {ROOT}\")\nlog(f\"stage3 input: {STAGE3}\")\nlog(f\"DINOv2: {DINO}\")\n\nif DINO is None:\n    raise FileNotFoundError(\n        \"DINOv2-small model directory not found. Attach the same DINO input used before.\"\n    )","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:27.072517Z","iopub.execute_input":"2026-08-11T20:59:27.07312Z","iopub.status.idle":"2026-08-11T20:59:27.445753Z","shell.execute_reply.started":"2026-08-11T20:59:27.073087Z","shell.execute_reply":"2026-08-11T20:59:27.445156Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"07812408","cell_type":"markdown","source":"## 1. Validate Notebook 03 handoff","metadata":{}},{"id":"4beb16ae","cell_type":"code","source":"stage3_status = json.loads((STAGE3 / \"stage3_status.json\").read_text())\nstage3_manifest = json.loads((STAGE3 / \"manifest.json\").read_text())\n\nif not stage3_status.get(\"stage3_ok\"):\n    raise RuntimeError(\"Stage 3 did not finish successfully\")\nif stage3_status.get(\"stage\") != \"FT-B_HARD_EXAMPLE\":\n    raise RuntimeError(f\"Unexpected Stage 3 type: {stage3_status.get('stage')!r}\")\n\nmembers = stage3_manifest.get(\"members\", [])\nif not members:\n    raise RuntimeError(\"Stage 3 manifest has no members\")\n\n# Stage 3 OOF already carries the 58 expert labels and the new expert-CV fold.\noof3 = pd.read_csv(\n    STAGE3 / \"expert_cv_predictions_stage3.csv\",\n    dtype={\"StudyInstanceUID\": str},\n)\ntarget_diag3 = pd.read_csv(STAGE3 / \"expert_cv_target_auc_stage3.csv\")\nbranch3 = pd.read_csv(STAGE3 / \"expert_cv_branch_summary.csv\")\n\nrequired_cols = {\"StudyInstanceUID\", \"ft_fold\", *TARGETS}\nmissing = required_cols.difference(oof3.columns)\nif missing:\n    raise RuntimeError(f\"Stage 3 OOF is missing columns: {sorted(missing)}\")\n\nexpert = oof3[[\"StudyInstanceUID\", \"ft_fold\", *TARGETS]].copy()\n\nprint(\"Stage 3 members:\", len(members))\nprint(\"Expert studies:\", len(expert))\nprint(\"Stage 3 promoted:\", stage3_status.get(\"n_promoted\"))\nprint(\"Stage 3 rolled back:\", stage3_status.get(\"n_rolled_back_to_fta\"))\ndisplay(branch3)\ndisplay(target_diag3)\n\nprint(\"FT-C specialist targets:\", SPECIALIST_TARGETS)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:30.50471Z","iopub.execute_input":"2026-08-11T20:59:30.505105Z","iopub.status.idle":"2026-08-11T20:59:30.535904Z","shell.execute_reply.started":"2026-08-11T20:59:30.505077Z","shell.execute_reply":"2026-08-11T20:59:30.535286Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"3c5c233d","cell_type":"markdown","source":"## 2. Recover checkpoint pixel configuration","metadata":{}},{"id":"63756306","cell_type":"code","source":"def slot_scheme_for_names(names):\n    names = list(names)\n    rec = [x[0] for x in SLOTS_RECOVERED]\n    pub = [x[0] for x in SLOTS_PUBLIC]\n    if names == rec:\n        return SLOTS_RECOVERED\n    if names == pub:\n        return SLOTS_PUBLIC\n    raise WeightsError(f\"Unknown checkpoint slot scheme: {names}\")\n\n\ndef adopt_config_globals(cfg):\n    global IMG, CACHE_IMG, GROUP, CACHE_SLICES, N_GROUP, CROP_MM\n    global SLICE_BAND, RULES, SLOTS, N_SLOT\n\n    CACHE_IMG = IMG = int(cfg[\"img\"])\n    GROUP = int(cfg[\"group\"])\n    CACHE_SLICES = int(cfg[\"slices\"])\n    N_GROUP = max(CACHE_SLICES // GROUP, 1)\n    CROP_MM = float(cfg[\"crop_mm\"])\n    SLICE_BAND = tuple(float(x) for x in cfg[\"band\"])\n\n    rules = cfg.get(\"rules\") or RULES_NATIVE\n    unknown = {\n        k: v for k, v in rules.items()\n        if k not in RULES_NATIVE or v not in (RULES_NATIVE[k], RULES_LEGACY[k])\n    }\n    if unknown:\n        raise WeightsError(f\"unsupported pixel rules in manifest: {unknown}\")\n    RULES = {**RULES_NATIVE, **rules}\n\n    SLOTS = slot_scheme_for_names(cfg[\"slots\"])\n    N_SLOT = len(SLOTS)\n\n\npixel_groups = {}\nfor m in members:\n    if not (STAGE3 / str(m[\"file\"])).is_file():\n        raise FileNotFoundError(STAGE3 / str(m[\"file\"]))\n    pixel_groups.setdefault(m[\"pixel_group\"], []).append(m)\n\nif not pixel_groups:\n    raise RuntimeError(\"No Stage-3 pixel groups were discovered\")\nprint(f\"Stage-3 checkpoint preflight passed: {len(members)} member(s)\")\n\ndisplay(pd.DataFrame([\n    {\n        \"id\": m.get(\"id\"),\n        \"base_fold\": m.get(\"fold\"),\n        \"ft_val_fold\": m.get(\"ft_val_fold\"),\n        \"ft_a_promoted\": m.get(\"ft_promoted\"),\n        \"file\": m.get(\"file\"),\n    }\n    for m in members\n]).sort_values(\"base_fold\"))\n\nprint(\"pixel groups:\", len(pixel_groups))\nfor k, gm in pixel_groups.items():\n    cfg = json.loads(k)\n    print(\n        f\"- {cfg['img']}px, slices={cfg['slices']}, group={cfg['group']}, \"\n        f\"crop={cfg['crop_mm']}mm -> {len(gm)} member(s)\"\n    )","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:33.377445Z","iopub.execute_input":"2026-08-11T20:59:33.37839Z","iopub.status.idle":"2026-08-11T20:59:33.399486Z","shell.execute_reply.started":"2026-08-11T20:59:33.378358Z","shell.execute_reply":"2026-08-11T20:59:33.398675Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"65e41758","cell_type":"markdown","source":"## 3. Reuse the exact successful Notebook 03 preprocessing/model contract","metadata":{}},{"id":"5d5ee2f6","cell_type":"code","source":"HDR_TAGS = [\"SeriesDescription\", \"SequenceName\", \"ScanOptions\", \"ScanningSequence\",\n            \"RepetitionTime\", \"EchoTime\", \"Laterality\", \"PixelSpacing\", \"Rows\",\n            \"Columns\", \"RescaleSlope\", \"RescaleIntercept\",\n            # Position and orientation are read from the same header probe() already\n            # opens, so they cost nothing, and they are what recovers the side when the\n            # Laterality tag is absent - which it is for half the studies here.\n            \"ImagePositionPatient\", \"ImageOrientationPatient\"]\n\n\ndef _hdr_vec(s, n):\n    \"\"\"Parse a DICOM multi-value string as stored by probe(): floats joined by `|`.\"\"\"\n    if not isinstance(s, str):\n        return None\n    try:\n        v = [float(x) for x in s.split(\"|\")]\n    except ValueError:\n        return None\n    return np.array(v) if len(v) >= n else None\n\n\ndef side_from_geometry(h):\n    \"\"\"Study -> 'L' / 'R' / None, from where the image sits in the patient.\n\n    `Laterality` (0020,0060) is Type 2C and may legitimately be absent; in this corpus it\n    is missing on exactly half the studies, and the vendors it is missing from are whole\n    vendors rather than scattered series. A study with no tag is not a left knee, but the\n    normalisation upstream treats it as one, so half the corpus was never normalised and\n    the five side-defined targets - the two menisci, the two tibiofemoral compartments\n    and the medial collateral ligament - saw that axis reversed on a large minority of it.\n\n    The patient coordinate system fixes this without the tag: +x is the patient's left, so\n    the centre of a right knee sits at negative x. The centre is used rather than\n    `ImagePositionPatient` itself because that is the corner of the image, which is offset\n    by half a field of view - enough to change the sign on a knee near the midline.\n\n    The median over a study's series is what is thresholded, not a single series: probe()\n    reads one arbitrary slice per series, which on a sagittal stack can sit anywhere\n    across the joint. Studies whose centre falls near the midline are left unresolved\n    rather than guessed - measured against the tagged half, the rule is right 97% of the\n    time overall and no better than chance inside 20 mm.\n    \"\"\"\n    cx = {}\n    for r in h.itertuples(index=False):\n        ipp = _hdr_vec(getattr(r, \"ImagePositionPatient\", None), 3)\n        iop = _hdr_vec(getattr(r, \"ImageOrientationPatient\", None), 6)\n        ps = _hdr_vec(getattr(r, \"PixelSpacing\", None), 2)\n        rows, cols = getattr(r, \"Rows\", None), getattr(r, \"Columns\", None)\n        if ipp is None or iop is None or ps is None or not rows or not cols:\n            continue\n        try:\n            c = ipp[:3] + iop[:3] * ps[1] * float(cols) / 2 + iop[3:6] * ps[0] * float(rows) / 2\n        except (TypeError, ValueError):\n            continue\n        cx.setdefault(r.StudyInstanceUID, []).append(float(c[0]))\n    out = {}\n    for st, xs in cx.items():\n        m = float(np.median(xs))\n        out[st] = None if abs(m) < LAT_MIN_OFFSET_MM else (\"R\" if m < 0 else \"L\")\n    return out\n\n\ndef side_from_corner_x(h):\n    \"\"\"The laterality an imported member was fitted under.\n\n    It thresholds the median raw `ImagePositionPatient` x over a study's series. That is\n    the x of the image *corner*, not of its centre, so it differs from the rule above by\n    up to half a field of view - which is enough to reverse the sign on a knee scanned\n    near the midline. The dead zone is 5 mm rather than 20 mm, so it also commits on\n    studies the rule above leaves unresolved.\n\n    Neither difference changes a shape. Each one decides whether a study is mirrored, and\n    a study mirrored one way at training and the other at inference presents the five\n    side-defined targets with their axis reversed.\n    \"\"\"\n    out = {}\n    for st, g in h.groupby(\"StudyInstanceUID\"):\n        xs = []\n        for r in g.itertuples(index=False):\n            ipp = _hdr_vec(getattr(r, \"ImagePositionPatient\", None), 3)\n            if ipp is not None and np.isfinite(ipp).all():\n                xs.append(float(ipp[0]))\n        if not xs:\n            out[st] = None\n            continue\n        x = float(np.median(xs))\n        # DICOM patient coordinates are LPS: +x is the patient's left.\n        out[st] = None if abs(x) < LEGACY_LAT_OFFSET_MM else (\"R\" if x < 0 else \"L\")\n    return out\n\n\ndef lat_of(h, tag=\"\"):\n    \"\"\"Study -> 'L' / 'R' / None: the tag where it exists, geometry where it does not.\n\n    The tag is present on exactly half the studies here and is sometimes an empty\n    string rather than absent, which is not the same as NaN. Treating the other half\n    as left-sided is what `normalise_laterality` did by omission, so the geometry\n    fallback is not a refinement - it is the difference between normalising half the\n    corpus and normalising all of it.\n    \"\"\"\n    geo = side_from_corner_x(h) if RULES[\"lat\"] == \"corner_x\" else side_from_geometry(h)\n    d, n_tag, n_geo, n_none, n_disagree = {}, 0, 0, 0, 0\n    for st, g in h.groupby(\"StudyInstanceUID\"):\n        v = [str(x).strip().upper() for x in g[\"Laterality\"].dropna()]\n        if RULES[\"lat\"] == \"corner_x\" and \"ImageLaterality\" in g.columns:\n            # The legacy rule reads the second tag too, so a study tagged only there is\n            # resolved from the tag rather than from geometry.\n            v += [str(x).strip().upper() for x in g[\"ImageLaterality\"].dropna()]\n        v = [x[0] for x in v if x and x[0] in (\"L\", \"R\")]\n        side = v[0] if v else None\n        if side is not None:\n            n_tag += 1\n            if geo.get(st) is not None and geo[st] != side:\n                n_disagree += 1\n        else:\n            side = geo.get(st)\n            n_geo += side is not None\n            n_none += side is None\n        d[st] = side\n    log(f\"{tag}laterality: {n_tag} from the tag, {n_geo} from geometry, \"\n        f\"{n_none} unresolved; tag and geometry disagree on {n_disagree} \"\n        f\"({n_disagree / max(n_tag, 1):.1%} of the tagged)\")\n    return d\n\n\n\ndef probe(item):\n    split, study, series, path = item\n    row = {\"split\": split, \"StudyInstanceUID\": study, \"SeriesInstanceUID\": series,\n           \"dir\": path}\n    try:\n        files = sorted(e.name for e in os.scandir(path) if e.name.endswith(\".dcm\"))\n        row[\"files\"] = files\n        row[\"n_slices\"] = len(files)\n        if not files:\n            return row\n        ds = pydicom.dcmread(os.path.join(path, files[len(files) // 2]),\n                             stop_before_pixels=True, force=True)\n        for t in HDR_TAGS:\n            v = getattr(ds, t, None)\n            if v is None:\n                row[t] = None\n            elif isinstance(v, (list, tuple)) or type(v).__name__ == \"MultiValue\":\n                row[t] = \"|\".join(str(x) for x in v)\n            else:\n                row[t] = str(v)\n    except Exception as exc:\n        row[\"err\"] = str(exc)[:120]\n    return row\n\n\ndef walk(split):\n    \"\"\"Every series directory of a split, with one header read per series.\n\n    An absent split returns an empty frame *with the columns annotate expects*. Returning\n    a bare DataFrame looks like the same thing and is not: the next call indexes\n    `SeriesDescription` and raises KeyError, so the branch that exists to survive a\n    missing split is what turns it into a crash.\n    \"\"\"\n    base = ROOT / split\n    items = []\n    if not base.is_dir():\n        return pd.DataFrame(columns=[\"split\", \"StudyInstanceUID\", \"SeriesInstanceUID\",\n                                     \"dir\", \"files\", \"n_slices\"] + HDR_TAGS)\n    for study in os.scandir(base):\n        if study.is_dir():\n            for series in os.scandir(study.path):\n                if series.is_dir():\n                    items.append((split, study.name, series.name, series.path))\n    with ThreadPoolExecutor(max_workers=HDR_THREADS) as pool:\n        rows = list(pool.map(probe, items))\n    return pd.DataFrame(rows)\n\n\ndef annotate(df):\n    \"\"\"Recover fat suppression and pulse-sequence weighting from the header.\"\"\"\n    desc = (df[\"SeriesDescription\"].fillna(\"\") + \" \" + df[\"SequenceName\"].fillna(\"\"))\n    desc = desc.str.lower().str.replace(_SEP, \" \", regex=True)\n\n    opts = df[\"ScanOptions\"].fillna(\"\").str.upper().str.split(\"|\")\n    # GE writes SAT_GEMS for spatial saturation, so ScanOptions must be matched as\n    # exact tokens; a substring test on \"SAT\" fires on non-fat-sat series.\n    opts_fs = opts.apply(lambda ts: any(t.strip() in FATSAT_OPTS for t in ts))\n    df[\"fatsat\"] = desc.str.contains(_FATSAT_RX) | opts_fs\n\n    tr = pd.to_numeric(df[\"RepetitionTime\"], errors=\"coerce\")\n    te = pd.to_numeric(df[\"EchoTime\"], errors=\"coerce\")\n    gre = df[\"ScanningSequence\"].fillna(\"\").str.upper().str.contains(\"GR\")\n    t1, t2, pdw = desc.str.contains(_T1_RX), desc.str.contains(_T2_RX), desc.str.contains(_PD_RX)\n\n    df[\"weight\"] = np.where(t1 & ~t2 & ~pdw, \"T1\",\n                     np.where(t2 & ~pdw, \"T2\",\n                       np.where(pdw, \"PD\",\n                         np.where(gre, \"GRE\",\n                           np.where(tr < 800, \"T1\",\n                             np.where(te > 60, \"T2\",\n                               np.where(tr >= 800, \"PD\", \"UNK\")))))))\n    df[\"fluid\"] = np.isin(df[\"weight\"], [\"PD\", \"T2\"])\n    df[\"px\"] = pd.to_numeric(\n        df[\"PixelSpacing\"].fillna(\"\").str.split(\"|\").str[0].replace(\"\", np.nan),\n        errors=\"coerce\")\n    return df","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:36.17349Z","iopub.execute_input":"2026-08-11T20:59:36.173754Z","iopub.status.idle":"2026-08-11T20:59:36.197043Z","shell.execute_reply.started":"2026-08-11T20:59:36.173732Z","shell.execute_reply":"2026-08-11T20:59:36.196448Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"cbbe70b2","cell_type":"code","source":"def walk_selected(split, study_ids):\n    study_ids = {str(x) for x in study_ids}\n    base = ROOT / split\n    items = []\n\n    if not base.is_dir():\n        raise FileNotFoundError(base)\n\n    for study_id in sorted(study_ids):\n        study_dir = base / study_id\n        if not study_dir.is_dir():\n            continue\n        for series in os.scandir(study_dir):\n            if series.is_dir():\n                items.append((split, study_id, series.name, series.path))\n\n    with ThreadPoolExecutor(max_workers=HDR_THREADS) as pool:\n        rows = list(pool.map(probe, items))\n\n    out = pd.DataFrame(rows)\n    if out.empty:\n        raise RuntimeError(f\"No DICOM series found for {len(study_ids)} selected studies\")\n    return out","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:41.358871Z","iopub.execute_input":"2026-08-11T20:59:41.359586Z","iopub.status.idle":"2026-08-11T20:59:41.36534Z","shell.execute_reply.started":"2026-08-11T20:59:41.359555Z","shell.execute_reply":"2026-08-11T20:59:41.364407Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"68b69dfd","cell_type":"code","source":"def _as_bool(v):\n    if pd.isna(v):\n        return None\n    s = str(v).strip().upper()\n    if s in {\"1\", \"TRUE\", \"T\", \"YES\", \"Y\"}:\n        return True\n    if s in {\"0\", \"FALSE\", \"F\", \"NO\", \"N\"}:\n        return False\n    try:\n        f = float(s)\n        return True if f == 1 else False if f == 0 else None\n    except Exception:\n        return None\n\n\ndef audit_official_sequence_metadata(inferred, official):\n    \"\"\"Audit only. Do not change imported checkpoint pixels from this table.\"\"\"\n    need = {\"SeriesInstanceUID\", \"Fluid_Sensitive\", \"Fat_Suppression\"}\n    if inferred.empty or official.empty or not need.issubset(official.columns):\n        return\n    a = inferred[[\"SeriesInstanceUID\", \"fluid\", \"fatsat\"]].copy()\n    b = official[[\"SeriesInstanceUID\", \"Fluid_Sensitive\", \"Fat_Suppression\"]].copy()\n    b[\"official_fluid\"] = b[\"Fluid_Sensitive\"].map(_as_bool)\n    b[\"official_fatsat\"] = b[\"Fat_Suppression\"].map(_as_bool)\n    m = a.merge(b[[\"SeriesInstanceUID\", \"official_fluid\", \"official_fatsat\"]],\n                on=\"SeriesInstanceUID\", how=\"inner\")\n    for inferred_col, official_col, name in [\n        (\"fluid\", \"official_fluid\", \"Fluid_Sensitive\"),\n        (\"fatsat\", \"official_fatsat\", \"Fat_Suppression\"),\n    ]:\n        valid = m[official_col].notna() & m[inferred_col].notna()\n        if valid.any():\n            agree = (m.loc[valid, inferred_col].astype(bool).values ==\n                     m.loc[valid, official_col].astype(bool).values).mean()\n            log(f\"metadata audit {name}: {agree:.1%} agreement on {int(valid.sum())} series\")","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:43.553466Z","iopub.execute_input":"2026-08-11T20:59:43.55373Z","iopub.status.idle":"2026-08-11T20:59:43.561398Z","shell.execute_reply.started":"2026-08-11T20:59:43.553707Z","shell.execute_reply":"2026-08-11T20:59:43.560604Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"208decc8","cell_type":"code","source":"def pick_slots(series_df, plane_map):\n    \"\"\"One series per slot per study.\n\n    Ties are broken toward the stack with the most slices: a thicker stack samples the\n    joint more densely, and the three-slice sampler below benefits from the margin.\n    \"\"\"\n    series_df = series_df.copy()\n    series_df[\"plane\"] = series_df[\"SeriesInstanceUID\"].map(plane_map)\n    out = {}\n    for study, g in series_df.groupby(\"StudyInstanceUID\"):\n        chosen = {}\n        for name, plane, fluid, fs in SLOTS:\n            sel = (g[\"plane\"] == plane) & (g[\"fatsat\"] == fs)\n            # fluid=None means \"do not condition on weighting\" - the public scheme,\n            # where the single provided flag stands in for both axes at once.\n            if fluid is not None:\n                sel &= (g[\"fluid\"] == fluid)\n            cand = g[sel]\n            # A slot with no series matching its predicate stays empty, and no substitute\n            # is admitted from a neighbouring predicate. Relaxing the weighting to fill a\n            # T1 slot would draw from the pool `SAG_FLUID_NOFS` selects from, since that\n            # pool is what remains once the weighting is dropped: over the training corpus\n            # it would put one series in two slots for 2383 of 4407 studies and leave 56%\n            # of the T1 slot holding PD or T2. The presence mask would then assert a\n            # sequence that was never acquired, and the per-diagnosis softmax of §6 would\n            # divide its attention across two identical slots, giving one acquisition\n            # about twice the weight it carries in a study that holds both. The mask is\n            # there to say a slot is absent, which is what an absent slot is.\n            if len(cand) == 0 and RULES[\"slot_fallback\"] and fluid is False:\n                # The relaxation the paragraph above rejects, reproduced because an\n                # imported member was fitted with its T1 slots filled this way: over half\n                # of that member's training studies had a T1 slot holding a series that\n                # is not T1. Leaving those slots empty would present it with a presence\n                # mask it never saw.\n                cand = g[(g[\"plane\"] == plane) & (~g[\"fatsat\"])]\n            if len(cand):\n                chosen[name] = cand.sort_values(\"n_slices\", ascending=False).iloc[0]\n        out[study] = chosen\n    return out","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:43.903899Z","iopub.execute_input":"2026-08-11T20:59:43.904305Z","iopub.status.idle":"2026-08-11T20:59:43.910809Z","shell.execute_reply.started":"2026-08-11T20:59:43.904277Z","shell.execute_reply":"2026-08-11T20:59:43.910117Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"2a7d4e85","cell_type":"code","source":"ORDER_TAGS = [(0x0020, 0x0032), (0x0020, 0x0037), (0x0020, 0x0013)]\n\n# Series in which at least one sampled slice would not decode. A list rather than a\n# counter because appending is atomic under the reader threads, and reported rather than\n# swallowed: unreported, a decode failure is indistinguishable from a black knee.\nDECODE_FAILED = []\n\n\ndef cache_tag(rules=None):\n    \"\"\"The name a decoded cache is stored under.\n\n    It has to name everything that decides the pixels, not only their dimensions. Two\n    configurations that agree on resolution, slice count, crop and band but disagree on\n    how a slice is chosen produce different arrays of identical shape - so a tag built\n    from the dimensions alone lets the second attach to the first one's file and train\n    against pixels it never asked for, with nothing anywhere reporting a mismatch.\n\n    A native reading keeps the plain name, so caches decoded before the rules existed\n    stay valid; anything else earns a suffix.\n    \"\"\"\n    r = dict(RULES if rules is None else rules)\n    t = (f\"{CACHE_IMG}px_{CACHE_SLICES}sl_{int(CROP_MM)}mm_\"\n         f\"{SLICE_BAND[0]:.2f}-{SLICE_BAND[1]:.2f}\")\n    if {k: r.get(k, v) for k, v in RULES_NATIVE.items()} != RULES_NATIVE:\n        t += \"_\" + hashlib.md5(json.dumps(r, sort_keys=True).encode()).hexdigest()[:6]\n    return t\n\n\ndef _natural_key(name):\n    return tuple(int(x) if x.isdigit() else x.lower()\n                 for x in re.split(r\"(\\d+)\", str(name)))\n\n\ndef _order_dominant_axis(rec):\n    \"\"\"The slice order an imported member was fitted under.\n\n    It sorts on the raw patient coordinate along whichever axis varies most across the\n    stack, rather than on the projection onto the slice normal. The two differ by a sign,\n    not by a formula: measured over this corpus every sagittal series has a slice normal\n    with n_x in [-1.00, -0.98], so p.n is the negative of the raw x this sorts on and the\n    two stacks come out exactly reversed. Because the band sampler truncates rather than\n    rounds, its nine indices are not symmetric about the middle, so nine slices drawn from\n    a twenty-six slice stack under one order share two with the other.\n\n    Missing geometry falls back to `InstanceNumber` and then to a natural sort of the file\n    name, both at the same 80% threshold the imported pipeline used.\n    \"\"\"\n    files, d = rec[\"files\"], rec[\"dir\"]\n    rows = []\n    for pos, f in enumerate(files):\n        ipp = inst = None\n        try:\n            ds = pydicom.dcmread(os.path.join(d, f), force=True, stop_before_pixels=True,\n                                 specific_tags=[\"ImagePositionPatient\", \"InstanceNumber\"])\n            raw = getattr(ds, \"ImagePositionPatient\", None)\n            if raw is not None and len(raw) >= 3:\n                c = np.asarray(raw[:3], dtype=np.float64)\n                if np.isfinite(c).all():\n                    ipp = c\n            n = getattr(ds, \"InstanceNumber\", None)\n            if n is not None:\n                inst = float(n)\n        except Exception:\n            pass\n        rows.append((f, ipp, inst, pos))\n\n    placed = [r for r in rows if r[1] is not None]\n    need = max(2, int(0.8 * len(rows)))\n    if len(placed) >= need:\n        xyz = np.stack([r[1] for r in placed])\n        axis = int(np.argmax(np.ptp(xyz, axis=0)))\n        spare = float(np.nanmedian(xyz[:, axis]))\n        rows.sort(key=lambda r: (float(r[1][axis]) if r[1] is not None else spare,\n                                 r[2] if r[2] is not None else float(\"inf\"), r[3]))\n    elif sum(r[2] is not None for r in rows) >= need:\n        rows.sort(key=lambda r: (r[2] if r[2] is not None else float(\"inf\"), r[3]))\n    else:\n        rows.sort(key=lambda r: _natural_key(r[0]))\n    return [r[0] for r in rows], True\n\n\ndef order_slices(rec):\n    \"\"\"Return the series' files sorted along the through-plane axis.\n\n    A DICOM file name here is a SOP Instance UID, which is assigned arbitrarily. Sorting\n    by it therefore produces an order uncorrelated with anatomy - measured over one\n    series, Spearman between file-name rank and physical position is 0.009, i.e. none.\n    Anything that assumes the file order means something is then operating on noise: the\n    three channels of a \"2.5D\" input are three unrelated views rather than neighbouring\n    slices, \"the middle of the stack\" is a random subset, and reversing slice order to\n    normalise laterality reverses nothing meaningful.\n\n    The physical order is recoverable exactly. Each slice carries its position in patient\n    coordinates and the in-plane axes; projecting the position onto the slice normal\n    gives a signed through-plane coordinate, monotonic along the stack:\n\n        n = r_x  x  r_y ,      k = p . n\n\n    `InstanceNumber` is the fallback. It usually tracks the projection up to sign, but\n    interleaved and multi-echo acquisitions need not number slices in the order they\n    occupy in space - but the projection is signed in patient\n    coordinates, which is what laterality normalisation needs.\n    \"\"\"\n    if RULES[\"order\"] == \"dominant_axis\":\n        return _order_dominant_axis(rec)\n    files, d = rec[\"files\"], rec[\"dir\"]\n    keyed = []\n    for f in files:\n        k = None\n        try:\n            ds = pydicom.dcmread(os.path.join(d, f), force=True, stop_before_pixels=True,\n                                 specific_tags=ORDER_TAGS)\n            iop = np.asarray(ds.ImageOrientationPatient, dtype=float)\n            ipp = np.asarray(ds.ImagePositionPatient, dtype=float)\n            k = float(np.dot(ipp, np.cross(iop[:3], iop[3:])))\n        except Exception:\n            try:\n                k = float(ds.InstanceNumber)\n            except Exception:\n                k = None\n        keyed.append((k, f))\n    if any(k is None for k, _ in keyed):\n        # A series with no usable geometry keeps its arbitrary order; that is worse than\n        # sorting but better than dropping the series, and it is logged as a count.\n        return files, False\n    return [f for _, f in sorted(keyed, key=lambda t: t[0])], True\n\n\ndef read_slot(rec, n_slice=None, out_size=None):\n    \"\"\"`n_slice` physically spread slices from one series, at `out_size` pixels.\n\n    Returns uint8 [n_slice, out, out] normalised per-series to its 1st-99th\n    percentile. Percentiles rather than min/max because MR intensity has no absolute\n    scale and a single bright vessel would otherwise compress the whole dynamic range.\n\n    Reading is the expensive half of this pipeline, so the caller reads once at the\n    largest configuration it needs and derives the smaller ones from the returned buffer\n    rather than re-reading.\n    \"\"\"\n    n_slice = GROUP if n_slice is None else n_slice\n    out_size = IMG if out_size is None else out_size\n    files, d, px = rec.get(\"ordered\") or rec[\"files\"], rec[\"dir\"], rec[\"px\"]\n    n = len(files)\n    if n == 0:\n        return None\n    # Spread the samples over a central band of the stack: the outermost slices of a knee\n    # series are mostly soft tissue outside the joint. The band is a constant rather than\n    # a literal because how much of the stack is worth reading depends on how many slices\n    # are being taken - at three the middle is all that fits, while at sixteen the ends\n    # are worth having, and a Baker cyst sits at the posteromedial end of a sagittal one.\n    lo, hi = int(SLICE_BAND[0] * (n - 1)), int(SLICE_BAND[1] * (n - 1))\n    idx = np.unique(np.linspace(lo, hi, n_slice).astype(int)) if hi > lo else np.array([n // 2])\n    while len(idx) < n_slice:\n        idx = np.append(idx, idx[-1])\n\n    planes = []\n    for i in idx[:n_slice]:\n        try:\n            ds = pydicom.dcmread(os.path.join(d, files[int(i)]), force=True)\n            a = ds.pixel_array.astype(np.float32)\n            sl = float(getattr(ds, \"RescaleSlope\", 1) or 1)\n            ic = float(getattr(ds, \"RescaleIntercept\", 0) or 0)\n            a = a * sl + ic\n        except Exception:\n            a = None                      # no shape is known here; see below\n        planes.append(a)\n\n    # A slice that would not decode has no shape of its own, and inventing one is how a\n    # single unreadable file erases a whole series: a substitute allocated at the resize\n    # target while the decoded slices are still native makes the shape check below take\n    # the substitute as the authority and zero the good slices with it, leaving a black\n    # slot that the presence mask still reports as acquired.\n    #\n    # A failure is instead filled from the nearest slice that did decode - the same\n    # convention the sampler already uses when the band holds fewer distinct slices than\n    # were asked for - and a series where nothing decodes is reported absent, which the\n    # mask can express, rather than black, which it cannot.\n    got = [k for k, p in enumerate(planes) if p is not None]\n    if RULES[\"decode_fill\"] == \"zero\":\n        # What an imported member was fitted with: a failure becomes a zero plane at the\n        # resize target, which the shape check below then propagates to the whole slot.\n        # It is the behaviour the paragraph above describes and rejects, kept here only\n        # because that member's weights were learned against slots blacked out this way.\n        if not got:\n            DECODE_FAILED.append(rec.get(\"SeriesInstanceUID\", d))\n        planes = [np.zeros((out_size, out_size), np.float32) if p is None else p\n                  for p in planes]\n        got = list(range(len(planes)))\n    if not got:\n        DECODE_FAILED.append(rec.get(\"SeriesInstanceUID\", d))\n        return None\n    if len(got) < len(planes):\n        DECODE_FAILED.append(rec.get(\"SeriesInstanceUID\", d))\n        for k, p in enumerate(planes):\n            if p is None:\n                planes[k] = planes[min(got, key=lambda j: abs(j - k))]\n\n    # Slices of one series can still differ in matrix size - multi-echo and some\n    # reformats do - and those are genuinely not stackable.\n    shp = planes[0].shape\n    planes = [p if p.shape == shp else np.zeros(shp, np.float32) for p in planes]\n    vol = np.stack(planes)\n\n    # constant physical extent, then resize: PixelSpacing varies 3.4x across the corpus\n    if px and np.isfinite(px) and px > 0:\n        want = int(round(CROP_MM / px))\n        h, w = shp\n        if 16 < want < min(h, w):\n            cy, cx = h // 2, w // 2\n            half = want // 2\n            vol = vol[:, max(0, cy - half):cy + half, max(0, cx - half):cx + half]\n\n    lo_v, hi_v = np.percentile(vol, [1, 99])\n    vol = np.clip((vol - lo_v) / max(hi_v - lo_v, 1e-6), 0, 1)\n\n    t = torch.from_numpy(np.ascontiguousarray(vol)).unsqueeze(0)\n    t = F.interpolate(t, size=(out_size, out_size), mode=\"bilinear\", align_corners=False)\n    # uint8, not float32. These buffers queue up between the reader threads and the\n    # encoder, and at this size a float32 slot-series is several megabytes. Intensity is\n    # already normalised into [0, 1] here, so eight bits cost nothing that a bilinear\n    # resize has not already cost, and the queue is a quarter the size.\n    return (t.squeeze(0) * 255).round().clamp(0, 255).to(torch.uint8)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:47.945597Z","iopub.execute_input":"2026-08-11T20:59:47.946083Z","iopub.status.idle":"2026-08-11T20:59:47.970868Z","shell.execute_reply.started":"2026-08-11T20:59:47.946055Z","shell.execute_reply":"2026-08-11T20:59:47.97026Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"63a35498","cell_type":"code","source":"def normalise_laterality(img, plane, lat):\n    \"\"\"Map every knee onto a left-knee convention.\n\n    Coronal and axial views mirror under a horizontal flip. Sagittal stacks are not\n    mirror images of each other - the slice order runs medial-to-lateral in opposite\n    directions - so the channel order is reversed instead.\n    \"\"\"\n    if lat != \"R\":\n        return img\n    if plane in (\"Coronal\", \"Axial\"):\n        return torch.flip(img, dims=[-1])\n    return torch.flip(img, dims=[0])","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:48.23678Z","iopub.execute_input":"2026-08-11T20:59:48.237154Z","iopub.status.idle":"2026-08-11T20:59:48.242037Z","shell.execute_reply.started":"2026-08-11T20:59:48.237129Z","shell.execute_reply":"2026-08-11T20:59:48.241267Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"96f4f37d","cell_type":"code","source":"# Where the geometric slice order may be remembered between runs. Unset on the platform,\n# because each run gets a fresh machine and there is nothing to remember; set off it,\n# where the same corpus is cached again at every resolution and slice count and the order\n# is a function of neither. It is opt-in so that the scored run's behaviour is decided by\n# the code rather than by whether a file happens to be lying about.\nORDER_CACHE = os.environ.get(\"RSNA_ORDER_CACHE\") or None\n\n\ndef build_cache(slot_map, plane_map, lat_map, tag):\n    \"\"\"Decode every (study, slot) once into an in-memory uint8 array.\n\n    Fine-tuning revisits the same pixels every epoch. Reading them from the mount each\n    time would make the epoch count a function of I/O rather than of learning, so they\n    are decoded once and held as bytes: intensity has already been normalised into\n    [0, 1], and eight bits cost nothing a bilinear resize has not already cost.\n\n    CACHE_SLICES positions are kept per slot, which the training loop reads as N_GROUP\n    groups of GROUP consecutive channels.\n    \"\"\"\n    studies = sorted(slot_map)\n    sidx = {s: i for i, s in enumerate(studies)}\n    cache = np.zeros((len(studies), N_SLOT, CACHE_SLICES, IMG, IMG), np.uint8)\n    mask = np.zeros((len(studies), N_SLOT), np.float32)\n    log(f\"{tag}: cache {cache.shape} = {cache.nbytes / 1024 ** 3:.1f} GB\")\n\n    jobs = [(st, k, plane, slot_map[st][name])\n            for st in studies\n            for k, (name, plane, _, _) in enumerate(SLOTS)\n            if name in slot_map[st]]\n    n_job = len(jobs)\n\n    # Ordering first, and as its own pass. It reads one header per slice of every chosen\n    # series - far more file opens than the decode that follows - and on a network mount\n    # that is latency, not work, so it gets its own wider pool.\n    t_ord = time.time()\n    n_slice_total = sum(len(j[3][\"files\"]) for j in jobs)\n    log(f\"{tag}: ordering {len(jobs)} slot-series ({n_slice_total} slice headers)\")\n    ok = done = 0\n    CHUNK_O = 1024\n\n    # A remembered order, when one is offered. The projection depends on the DICOM\n    # geometry alone, so it is the same at every resolution and every slice count, and\n    # it costs one header read per slice - the largest single cost in this pass. An entry\n    # is validated by the number of files present, so a tree that has changed under it is\n    # recomputed rather than trusted: order is derived data, and a stale entry would be\n    # invisible in the way that matters most.\n    seen = {}\n    if ORDER_CACHE and Path(ORDER_CACHE).is_file():\n        try:\n            import json as _json\n            seen = _json.loads(Path(ORDER_CACHE).read_text())\n        except (OSError, ValueError):\n            seen = {}\n        hit = 0\n        for _, _, _, rec in jobs:\n            e = seen.get(rec[\"SeriesInstanceUID\"])\n            if e and len(e[\"files\"]) == len(rec[\"files\"]):\n                rec[\"ordered\"] = e[\"files\"]\n                ok += int(e[\"good\"])\n                hit += 1\n        jobs = [j for j in jobs if \"ordered\" not in j[3]]\n        log(f\"{tag}: {hit} slot-series ordered from {ORDER_CACHE}, {len(jobs)} to read\")\n\n    with ThreadPoolExecutor(max_workers=ORDER_THREADS) as pool:\n        for c0 in range(0, len(jobs), CHUNK_O):\n            block = jobs[c0:c0 + CHUNK_O]\n            for (_, _, _, rec), (files, good) in zip(\n                    block, pool.map(lambda j: order_slices(j[3]), block)):\n                rec[\"ordered\"] = files\n                ok += int(good)\n                done += 1\n                if ORDER_CACHE:\n                    seen[rec[\"SeriesInstanceUID\"]] = {\"files\": files, \"good\": bool(good)}\n            # The ceiling is whichever comes first: the pass's own budget, or the share\n            # of what is left of the run that it may take. The second is what makes the\n            # first safe to set generously - a mount slow enough to matter cannot spend\n            # the training time, because the budget shrinks as the run does.\n            budget = min(ORDER_BUDGET_S, max(60.0, (TIME_BUDGET - (time.time() - T0)) * 0.35))\n            if time.time() - t_ord > budget:\n                log(f\"{tag}: ordering budget spent at {done}/{len(jobs)}; \"\n                    f\"the rest keep file order\")\n                break\n    if ORDER_CACHE and done:\n        import json as _json\n        _t = Path(ORDER_CACHE).with_suffix(\".tmp\")\n        _t.write_text(_json.dumps(seen))\n        _t.replace(Path(ORDER_CACHE))\n    log(f\"{tag}: ordered {ok}/{n_job} by geometry \"\n        f\"({n_job - ok} kept arbitrary) in {time.time() - t_ord:.0f}s\")\n\n    jobs = [(st, k, plane, slot_map[st][name])\n            for st in studies\n            for k, (name, plane, _, _) in enumerate(SLOTS)\n            if name in slot_map[st]]\n    log(f\"{tag}: decoding {len(jobs)} slot-series\")\n    n_failed_before = len(DECODE_FAILED)\n\n    CHUNK = 512\n    done = 0\n    with ThreadPoolExecutor(max_workers=PIX_THREADS) as pool:\n        for c0 in range(0, len(jobs), CHUNK):\n            block = jobs[c0:c0 + CHUNK]\n            for (st, k, plane, _), img in zip(\n                    block, pool.map(lambda j: read_slot(j[3], CACHE_SLICES, IMG), block)):\n                done += 1\n                if img is None:\n                    continue\n                cache[sidx[st], k] = normalise_laterality(img, plane,\n                                                          lat_map.get(st)).numpy()\n                mask[sidx[st], k] = 1.0\n            if done % 4096 < CHUNK:\n                log(f\"  {tag} {done}/{len(jobs)}\")\n            if time.time() - T0 > TIME_BUDGET:\n                log(f\"  {tag}: time budget reached during decode\")\n                break\n    n_failed = len(DECODE_FAILED) - n_failed_before\n    log(f\"{tag}: {int(mask.sum())}/{len(jobs)} slots filled\"\n        + (f\"; {n_failed} series had a slice that would not decode\" if n_failed else \"\"))\n    gc.collect()\n    return studies, cache, mask","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:50.85278Z","iopub.execute_input":"2026-08-11T20:59:50.853544Z","iopub.status.idle":"2026-08-11T20:59:50.868908Z","shell.execute_reply.started":"2026-08-11T20:59:50.853513Z","shell.execute_reply":"2026-08-11T20:59:50.868262Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"210d8875","cell_type":"code","source":"class SlotHead(nn.Module):\n    \"\"\"Per-diagnosis attention over the slot embeddings of one study.\n\n    Each finding is read on particular sequences - cruciates sagittally, collateral\n    ligaments and the meniscal body coronally, patellar cartilage axially - so pooling\n    the slots identically would dilute the one that carries the evidence with the rest.\n\n    The aggregation is deliberately this simple. With a study-level label there is no\n    signal telling the model which part of a study matters, so extra attention\n    parameters below the slot level would have nothing to learn from and would spend\n    their capacity fitting noise.\n    \"\"\"\n\n    def __init__(self, dim, n_slot, n_out, hidden=256, p=0.2, prior=False):\n        super().__init__()\n        self.proj = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.GELU())\n        self.slot_emb = nn.Parameter(torch.randn(n_slot, hidden) * 0.02)\n        self.query = nn.Parameter(torch.randn(n_out, hidden) * 0.02)\n        self.drop = nn.Dropout(p)\n        self.out = nn.Linear(hidden, n_out)\n        self.hidden = hidden\n        # An imported member carries a fixed per-(diagnosis, slot) tilt on the attention\n        # logits, set from the anatomy table below rather than learned. It is a buffer, so\n        # it travels in the state dict and must exist for that member to load; exp(0.55)\n        # gives a preferred slot about 1.73x the weight of an unpreferred one, which\n        # biases the softmax without ever excluding a slot.\n        p_ = torch.zeros(n_out, n_slot)\n        if prior and n_slot == len(SLOTS) and n_out == len(TARGETS):\n            for t, slots in SLOT_PRIOR_TABLE.items():\n                if t in TARGETS:\n                    p_[TARGETS.index(t), list(slots)] = SLOT_PRIOR_STRENGTH\n        self.prior = prior\n        if prior:\n            self.register_buffer(\"slot_prior\", p_)\n\n    def forward(self, x, mask):\n        h = self.proj(x) + self.slot_emb\n        att = torch.einsum(\"bsh,oh->bos\", h, self.query) / self.hidden ** 0.5\n        if self.prior:\n            att = att + self.slot_prior.unsqueeze(0)\n        att = att.masked_fill(mask.unsqueeze(1) < 0.5, -1e4).softmax(-1)\n        ctx = self.drop(torch.einsum(\"bos,bsh->boh\", att, h))\n        return (ctx * self.out.weight.unsqueeze(0)).sum(-1) + self.out.bias","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:51.160003Z","iopub.execute_input":"2026-08-11T20:59:51.16069Z","iopub.status.idle":"2026-08-11T20:59:51.168721Z","shell.execute_reply.started":"2026-08-11T20:59:51.160658Z","shell.execute_reply":"2026-08-11T20:59:51.167889Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"bc2221ae","cell_type":"code","source":"class Model(nn.Module):\n    \"\"\"Encoder plus head, trained end to end.\n\n    A study arrives as a bag of slot images. The bag is flattened for the encoder and\n    folded back before the head, so the encoder never sees the study structure and the\n    head never sees pixels.\n    \"\"\"\n\n    def __init__(self, backbone, dim, pool=\"cls_mean\", prior=False):\n        super().__init__()\n        self.backbone = backbone\n        self.pool = pool\n        self.head = SlotHead(dim * POOL_PARTS[pool], N_SLOT, len(TARGETS), prior=prior)\n        self.register_buffer(\"mean\", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))\n        self.register_buffer(\"std\", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))\n\n    def forward(self, imgs, mask, img_size=None):\n        B, S = imgs.shape[:2]\n        x = imgs.reshape(B * S, *imgs.shape[2:]).float().div_(255.0)\n        if img_size is not None and img_size != x.shape[-1]:\n            # The cache is held at the highest resolution any configuration needs; the\n            # rest downsample from it, so every configuration sees the same pixels\n            # through a different sampling grid rather than a different crop.\n            x = F.interpolate(x, size=(img_size, img_size), mode=\"bilinear\",\n                              align_corners=False)\n        x = (x - self.mean) / self.std\n        out = self.backbone(pixel_values=x).last_hidden_state\n        patch = out[:, 1:]\n        parts = [out[:, 0], patch.mean(1)]\n        if self.pool == \"cls_mean_focal\":\n            # The upper tail of each channel over the patch grid, taken per channel\n            # rather than by selecting whole patches: a finding occupies a small part of\n            # the field, so a plain mean over 256 patches dilutes it by two orders of\n            # magnitude, and this keeps the top eighth of each channel's responses.\n            k = max(1, patch.shape[1] // 8)\n            parts.append(patch.topk(k, dim=1).values.mean(1))\n        feat = torch.cat(parts, dim=1).reshape(B, S, -1)\n        return self.head(feat, mask)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:52.815492Z","iopub.execute_input":"2026-08-11T20:59:52.815868Z","iopub.status.idle":"2026-08-11T20:59:52.824034Z","shell.execute_reply.started":"2026-08-11T20:59:52.815833Z","shell.execute_reply":"2026-08-11T20:59:52.82328Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"aaf3c830","cell_type":"code","source":"def build_model(unfreeze_last, source=None, variant=\"small\", pool=\"cls_mean\", prior=False):\n    from transformers import AutoModel\n\n    p = Path(source) if source is not None else DINO\n    if p is None:\n        raise FileNotFoundError(\"DINOv2 weights not attached\")\n\n    bb = AutoModel.from_pretrained(str(p))\n    n_layer = len(bb.encoder.layer)\n\n    for prm in bb.parameters():\n        prm.requires_grad = False\n\n    n_unfreeze = max(0, int(unfreeze_last))\n    if n_unfreeze > 0:\n        for blk in bb.encoder.layer[max(0, n_layer - n_unfreeze):]:\n            for prm in blk.parameters():\n                prm.requires_grad = True\n        # LayerNorm is only trainable when backbone fine-tuning is requested.\n        for prm in bb.layernorm.parameters():\n            prm.requires_grad = True\n\n    dim = bb.config.hidden_size\n    trainable = sum(p.numel() for p in bb.parameters() if p.requires_grad)\n    log(\n        f\"backbone: {n_layer} blocks, last {n_unfreeze} trainable \"\n        f\"({trainable / 1e6:.1f}M backbone params)\"\n    )\n    return Model(bb, dim, pool=pool, prior=prior)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:56.951871Z","iopub.execute_input":"2026-08-11T20:59:56.952509Z","iopub.status.idle":"2026-08-11T20:59:56.95899Z","shell.execute_reply.started":"2026-08-11T20:59:56.952481Z","shell.execute_reply":"2026-08-11T20:59:56.958108Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"b5dcee76","cell_type":"code","source":"FINGERPRINT_TOL = 2e-3\n\ndef fingerprint(model, dev, img_size, n_slot=None, group=None, seed=None):\n    n_slot = N_SLOT if n_slot is None else n_slot\n    group = GROUP if group is None else group\n    seed = SEED if seed is None else seed\n\n    g = torch.Generator().manual_seed(seed)\n    imgs = torch.randint(\n        0, 256, (2, n_slot, group, img_size, img_size),\n        generator=g, dtype=torch.uint8\n    ).to(dev)\n    mask = torch.ones(2, n_slot, device=dev)\n    mask[1, -1] = 0.0\n\n    was_training = model.training\n    model.eval()\n    with torch.no_grad():\n        out = model(imgs, mask, img_size).float().cpu().numpy()\n    if was_training:\n        model.train()\n    return out\n\n\ndef check_fingerprint(\n    model,\n    dev,\n    img_size,\n    expected,\n    tol=FINGERPRINT_TOL,\n    tag=\"\",\n    seed=None,\n):\n    # IMPORTANT: a stored fingerprint must be reproduced with the same\n    # deterministic synthetic-input seed that was used when it was saved.\n    got = fingerprint(model, dev, img_size, seed=seed)\n    exp = np.asarray(expected, np.float32)\n    if got.shape != exp.shape:\n        raise WeightsError(f\"{tag}fingerprint shape {got.shape} != stored {exp.shape}\")\n    d = float(np.abs(got - exp).max())\n    if d > tol:\n        raise WeightsError(\n            f\"{tag}fingerprint differs by {d:.4g} > {tol:g}; \"\n            \"architecture/preprocessing contract moved\"\n        )\n    log(f\"{tag}fingerprint matches within {d:.2g} (seed={seed})\")\n    return d\n\n\ndef window_starts(n_slice, group):\n    if n_slice >= group:\n        return list(range(n_slice - group + 1))\n    return [0]\n\n\ndef _apply_frontier_pool(probs):\n    v = probs.mean(dim=0)\n    target_idx = {t: j for j, t in enumerate(TARGETS)}\n    for target, mode in FRONTIER_TARGET_POOL.items():\n        j = target_idx[target]\n        x = probs[:, :, j]\n        if mode == \"max\":\n            v[:, j] = x.max(dim=0).values\n        elif mode.startswith(\"top\"):\n            k = min(int(mode[3:]), x.shape[0])\n            v[:, j] = x.topk(k, dim=0).values.mean(dim=0)\n        elif mode == \"mean\":\n            v[:, j] = x.mean(dim=0)\n        else:\n            raise ValueError(mode)\n    return v\n\n\n@torch.no_grad()\ndef predict_member_frontier(model, cache, mask, idx, dev, img_size):\n    starts = window_starts(cache.shape[2], GROUP)\n    model.eval()\n    pred = np.empty((len(idx), len(TARGETS)), np.float32)\n\n    for b0 in range(0, len(idx), EVAL_BATCH):\n        sel = np.asarray(idx[b0:b0 + EVAL_BATCH], dtype=int)\n        b1 = b0 + len(sel)\n        m = torch.from_numpy(mask[sel]).to(dev)\n        win = []\n\n        for st in starts:\n            rows = torch.from_numpy(\n                np.ascontiguousarray(cache[sel, :, st:st + GROUP])\n            ).to(dev)\n            with torch.autocast(device_type=dev.type, enabled=dev.type == \"cuda\"):\n                logits = model(rows, m, img_size).float()\n            win.append(torch.sigmoid(logits))\n\n        probs = torch.stack(win, dim=0)\n        pred[b0:b1] = _apply_frontier_pool(probs).cpu().numpy()\n\n    return pred","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:57.260343Z","iopub.execute_input":"2026-08-11T20:59:57.261023Z","iopub.status.idle":"2026-08-11T20:59:57.27425Z","shell.execute_reply.started":"2026-08-11T20:59:57.260997Z","shell.execute_reply":"2026-08-11T20:59:57.273488Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"f85067e3","cell_type":"markdown","source":"## 4. Decode the same 58 expert studies once per pixel group","metadata":{}},{"id":"84e3b870","cell_type":"code","source":"train_series = pd.read_csv(\n    ROOT / \"train_series.csv\",\n    dtype={\"StudyInstanceUID\": str, \"SeriesInstanceUID\": str},\n)\nplane_map = dict(zip(\n    train_series[\"SeriesInstanceUID\"].astype(str),\n    train_series[\"Anatomical_Plane\"],\n))\n\nexpert_ids = expert[\"StudyInstanceUID\"].astype(str).tolist()\nhtr = annotate(walk_selected(\"train_series\", expert_ids))\nlog(\n    f\"expert header pass: {len(htr)} series across \"\n    f\"{htr['StudyInstanceUID'].nunique()} studies\"\n)\n\ngroup_cache = {}\n\nfor gi, (pixel_key, gm) in enumerate(pixel_groups.items(), 1):\n    cfg = json.loads(pixel_key)\n    adopt_config_globals(cfg)\n\n    log(\n        f\"decode group {gi}/{len(pixel_groups)}: \"\n        f\"{IMG}px, {CACHE_SLICES} slices, group={GROUP}, crop={CROP_MM}mm\"\n    )\n\n    slot_map = pick_slots(htr, plane_map)\n    studies, cache, slot_mask = build_cache(\n        slot_map,\n        plane_map,\n        lat_of(htr, f\"expert g{gi} \"),\n        f\"expert g{gi}\",\n    )\n\n    group_cache[pixel_key] = {\n        \"studies\": studies,\n        \"cache\": cache,\n        \"slot_mask\": slot_mask,\n        \"cfg\": cfg,\n    }\n\n    log(\n        f\"g{gi}: cache {cache.shape}, slot coverage \"\n        f\"{slot_mask.sum():.0f}/{slot_mask.size}\"\n    )\n\nprint(\"cached pixel groups:\", len(group_cache))","metadata":{"execution":{"iopub.status.busy":"2026-08-11T20:59:59.232033Z","iopub.execute_input":"2026-08-11T20:59:59.232882Z","iopub.status.idle":"2026-08-11T21:00:38.683041Z","shell.execute_reply.started":"2026-08-11T20:59:59.232849Z","shell.execute_reply":"2026-08-11T21:00:38.682305Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"5b70037b","cell_type":"markdown","source":"## 5. Specialist-only optimization utilities","metadata":{}},{"id":"0d9260fb","cell_type":"code","source":"def align_training_arrays(studies):\n    e = expert.set_index(\"StudyInstanceUID\").loc[list(studies)]\n    y = e[TARGETS].to_numpy(np.float32)\n    label_mask = np.isfinite(y).astype(np.float32)\n    y = np.nan_to_num(y, nan=0.0)\n    folds = e[\"ft_fold\"].to_numpy(np.int64)\n    return y, label_mask, folds\n\n\ndef prob_bce(pred, y, mask, target_idx=None):\n    p = np.clip(np.asarray(pred, np.float64), 1e-6, 1 - 1e-6)\n    yy = np.asarray(y, np.float64)\n    mm = np.asarray(mask, np.float64)\n\n    if target_idx is not None:\n        p = p[:, target_idx]\n        yy = yy[:, target_idx]\n        mm = mm[:, target_idx]\n\n    per = -(yy * np.log(p) + (1 - yy) * np.log(1 - p))\n    return float((per * mm).sum() / max(mm.sum(), 1.0))\n\n\ndef macro_auc(pred, y, mask, target_idx=None):\n    indices = list(range(len(TARGETS))) if target_idx is None else list(map(int, target_idx))\n    vals = []\n    per_target = {}\n\n    for j in indices:\n        t = TARGETS[j]\n        valid = mask[:, j] > 0.5\n        yy = y[valid, j]\n        pp = pred[valid, j]\n        if len(np.unique(yy)) < 2:\n            per_target[t] = np.nan\n            continue\n        a = float(roc_auc_score(yy, pp))\n        per_target[t] = a\n        vals.append(a)\n\n    return (float(np.mean(vals)) if vals else np.nan), per_target\n\n\ndef make_pos_weight(y, label_mask, idx):\n    yy = y[idx][:, SPECIALIST_IDX]\n    mm = label_mask[idx][:, SPECIALIST_IDX]\n    pos = (yy * mm).sum(axis=0)\n    known = mm.sum(axis=0)\n    neg = known - pos\n    ratio = np.sqrt((neg + 0.5) / (pos + 0.5))\n    ratio = np.clip(ratio, 1.0, 3.0)\n    return torch.tensor(ratio, dtype=torch.float32)\n\n\ndef configure_true_specialist(model):\n    # Freeze everything first.\n    for p in model.parameters():\n        p.requires_grad = False\n\n    # These tensors have one independent row per diagnosis.\n    model.head.query.requires_grad = True\n    model.head.out.weight.requires_grad = True\n    model.head.out.bias.requires_grad = True\n\n    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    log(f\"true specialist trainable parameters: {trainable:,}\")\n    return model\n\n\ndef specialist_bce_logits(logits, y, mask, pos_weight):\n    idx = torch.as_tensor(SPECIALIST_IDX, device=logits.device, dtype=torch.long)\n    z = logits.index_select(1, idx)\n    yy = y.index_select(1, idx)\n    mm = mask.index_select(1, idx)\n\n    per = F.binary_cross_entropy_with_logits(\n        z, yy, reduction=\"none\", pos_weight=pos_weight\n    )\n    return (per * mm).sum() / mm.sum().clamp_min(1.0)\n\n\ndef specialist_optimizer(model):\n    params = [p for p in model.parameters() if p.requires_grad]\n    if not params:\n        raise RuntimeError(\"No specialist parameters are trainable\")\n\n    # IMPORTANT:\n    # The entire query/out tensors contain rows for all 12 targets. Even when\n    # non-specialist rows have zero gradient, AdamW weight decay would still\n    # move them. Zero decay keeps those rows unchanged.\n    return torch.optim.AdamW(\n        params,\n        lr=FTC_HEAD_LR,\n        weight_decay=0.0,\n    )\n\n\ndef snapshot_non_specialist_rows(model):\n    non_spec = [j for j in range(len(TARGETS)) if j not in set(SPECIALIST_IDX.tolist())]\n    idx = torch.tensor(non_spec, dtype=torch.long, device=model.head.query.device)\n    return {\n        \"idx\": idx,\n        \"query\": model.head.query.detach().index_select(0, idx).clone(),\n        \"out_weight\": model.head.out.weight.detach().index_select(0, idx).clone(),\n        \"out_bias\": model.head.out.bias.detach().index_select(0, idx).clone(),\n    }\n\n\n@torch.no_grad()\ndef restore_non_specialist_rows(model, snap):\n    idx = snap[\"idx\"]\n    model.head.query.index_copy_(0, idx, snap[\"query\"])\n    model.head.out.weight.index_copy_(0, idx, snap[\"out_weight\"])\n    model.head.out.bias.index_copy_(0, idx, snap[\"out_bias\"])\n\n\ndef cpu_state_dict(model):\n    return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}\n\n\ndef better_specialist_candidate(\n    cand_spec_auc,\n    cand_spec_bce,\n    cand_full_auc,\n    best_spec_auc,\n    best_spec_bce,\n    parent_spec_bce,\n    parent_full_auc,\n):\n    # Never allow a large full-model ranking regression.\n    if np.isfinite(parent_full_auc) and np.isfinite(cand_full_auc):\n        if cand_full_auc < parent_full_auc - FTC_MAX_FULL_AUC_DROP:\n            return False\n\n    if np.isfinite(cand_spec_auc) and np.isfinite(best_spec_auc):\n        if (\n            cand_spec_auc > best_spec_auc + FTC_MIN_SPEC_AUC_GAIN\n            and cand_spec_bce <= parent_spec_bce + FTC_MAX_SPEC_BCE_WORSEN\n        ):\n            return True\n\n        if (\n            cand_spec_auc >= best_spec_auc - FTC_SPEC_AUC_TIE\n            and cand_spec_bce < best_spec_bce - FTC_SPEC_BCE_GAIN\n            and cand_spec_bce <= parent_spec_bce + FTC_MAX_SPEC_BCE_WORSEN\n        ):\n            return True\n\n        return False\n\n    # Tiny validation folds can make AUC undefined for a target group.\n    return cand_spec_bce < best_spec_bce - FTC_SPEC_BCE_GAIN\n\n\ndef train_one_specialist_epoch(\n    model,\n    cache,\n    slot_mask,\n    y,\n    label_mask,\n    train_idx,\n    dev,\n    optimizer,\n    scaler,\n    pos_weight,\n    epoch_seed,\n    non_specialist_snapshot,\n):\n    model.train()\n    rng = np.random.default_rng(epoch_seed)\n    order = np.asarray(train_idx, dtype=int).copy()\n    rng.shuffle(order)\n\n    optimizer.zero_grad(set_to_none=True)\n    losses = []\n    n_steps = math.ceil(len(order) / FTC_BATCH)\n\n    for step, b0 in enumerate(range(0, len(order), FTC_BATCH), 1):\n        sel = order[b0:b0 + FTC_BATCH]\n        starts = rng.integers(\n            0,\n            max(cache.shape[2] - GROUP + 1, 1),\n            size=len(sel),\n        )\n\n        x_np = np.stack(\n            [cache[i, :, int(st):int(st) + GROUP] for i, st in zip(sel, starts)],\n            axis=0,\n        )\n        x = torch.from_numpy(np.ascontiguousarray(x_np)).to(dev)\n        sm = torch.from_numpy(slot_mask[sel]).to(dev)\n        yy = torch.from_numpy(y[sel]).to(dev)\n        lm = torch.from_numpy(label_mask[sel]).to(dev)\n\n        with torch.autocast(device_type=dev.type, enabled=dev.type == \"cuda\"):\n            logits = model(x, sm, IMG)\n            loss = specialist_bce_logits(\n                logits, yy, lm, pos_weight.to(dev)\n            )\n            loss = loss / FTC_GRAD_ACCUM\n\n        scaler.scale(loss).backward()\n        losses.append(float(loss.detach().cpu()) * FTC_GRAD_ACCUM)\n\n        if step % FTC_GRAD_ACCUM == 0 or step == n_steps:\n            scaler.unscale_(optimizer)\n            torch.nn.utils.clip_grad_norm_(\n                [p for p in model.parameters() if p.requires_grad],\n                max_norm=1.0,\n            )\n            scaler.step(optimizer)\n            scaler.update()\n\n            # Hard guarantee: the 8 non-specialist target rows are bit-for-bit\n            # restored after every optimizer update.\n            restore_non_specialist_rows(model, non_specialist_snapshot)\n\n            optimizer.zero_grad(set_to_none=True)\n\n    return float(np.mean(losses)) if losses else np.nan","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:00:38.68418Z","iopub.execute_input":"2026-08-11T21:00:38.684491Z","iopub.status.idle":"2026-08-11T21:00:38.711272Z","shell.execute_reply.started":"2026-08-11T21:00:38.684467Z","shell.execute_reply":"2026-08-11T21:00:38.710624Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"d9af0679","cell_type":"markdown","source":"## 6. FT-C structural-specialist fine-tuning loop","metadata":{}},{"id":"12f8f260","cell_type":"code","source":"dev = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nlog(f\"device: {dev}\")\n\nmetrics_rows = []\nnew_members = []\n\nuid_order = expert[\"StudyInstanceUID\"].astype(str).tolist()\nuid_to_global = {u: i for i, u in enumerate(uid_order)}\noof_ftc_sum = np.zeros((len(expert), len(TARGETS)), np.float64)\noof_count = np.zeros(len(expert), np.int64)\n\noof3_idx = oof3.set_index(\"StudyInstanceUID\")\n\nfor mi, m in enumerate(members, 1):\n    if time.time() - T0 > TIME_BUDGET:\n        log(\"time budget reached before all Stage 3 parents were processed\")\n        break\n\n    pixel_key = m[\"pixel_group\"]\n    pack = group_cache[pixel_key]\n    pixel_cfg = pack[\"cfg\"]\n    member_cfg = m.get(\"config\") or {}\n    adopt_config_globals(pixel_cfg)\n\n    studies = pack[\"studies\"]\n    cache = pack[\"cache\"]\n    slot_mask = pack[\"slot_mask\"]\n    y, label_mask, ft_folds = align_training_arrays(studies)\n\n    val_fold = int(m.get(\"ft_val_fold\", m.get(\"fold\")))\n    train_idx = np.where(ft_folds != val_fold)[0]\n    val_idx = np.where(ft_folds == val_fold)[0]\n\n    log(\n        f\"[{mi}/{len(members)}] {m['id']} -> FT-C val-fold={val_fold}; \"\n        f\"train={len(train_idx)}, val={len(val_idx)}\"\n    )\n\n    ck_path = STAGE3 / str(m[\"file\"])\n    ck = torch.load(ck_path, map_location=\"cpu\", weights_only=False)\n\n    model = build_model(\n        0,\n        source=DINO,\n        variant=member_cfg.get(\"variant\", \"small\"),\n        pool=member_cfg.get(\"pool\", \"cls_mean\"),\n        prior=bool(member_cfg.get(\"prior\", False)),\n    ).to(dev)\n    model.load_state_dict(ck[\"model\"], strict=True)\n\n    if \"fingerprint\" in ck:\n        parent_fp_seed = int(\n            ck.get(\"fingerprint_seed\", stage3_status.get(\"fingerprint_seed\", 31415))\n        )\n        check_fingerprint(\n            model,\n            dev,\n            IMG,\n            ck[\"fingerprint\"],\n            tag=f\"{m['id']}: \",\n            seed=parent_fp_seed,\n        )\n    else:\n        parent_fp_seed = None\n\n    # Reproduce Stage 3 OOF before making any update.\n    parent_pred = predict_member_frontier(\n        model, cache, slot_mask, val_idx, dev, IMG\n    )\n    val_uids = [studies[int(i)] for i in val_idx]\n    expected = np.column_stack([\n        oof3_idx.loc[val_uids, f\"ftb__{t}\"].to_numpy(float)\n        for t in TARGETS\n    ])\n    parent_oof_maxdiff = float(np.max(np.abs(parent_pred - expected)))\n    log(f\"  parent-vs-Stage3 OOF max |diff| = {parent_oof_maxdiff:.3g}\")\n    if parent_oof_maxdiff > 5e-3:\n        raise WeightsError(\n            f\"{m['id']}: parent prediction mismatch {parent_oof_maxdiff:.4g}; \"\n            \"preprocessing/model contract is not reproducing Stage 3\"\n        )\n\n    parent_full_bce = prob_bce(parent_pred, y[val_idx], label_mask[val_idx])\n    parent_full_auc, _ = macro_auc(parent_pred, y[val_idx], label_mask[val_idx])\n    parent_spec_bce = prob_bce(\n        parent_pred, y[val_idx], label_mask[val_idx], SPECIALIST_IDX\n    )\n    parent_spec_auc, _ = macro_auc(\n        parent_pred, y[val_idx], label_mask[val_idx], SPECIALIST_IDX\n    )\n\n    # Freeze backbone + shared head representation. Only diagnosis-specific rows move.\n    configure_true_specialist(model)\n    non_specialist_snapshot = snapshot_non_specialist_rows(model)\n\n    best_spec_bce = parent_spec_bce\n    best_spec_auc = parent_spec_auc\n    best_full_bce = parent_full_bce\n    best_full_auc = parent_full_auc\n    best_epoch = 0\n    best_state = None\n    best_pred = parent_pred.copy()\n\n    pos_weight = make_pos_weight(y, label_mask, train_idx)\n    optimizer = specialist_optimizer(model)\n\n    def lr_factor(ep):\n        if FTC_MAX_EPOCHS <= 1:\n            return 1.0\n        x = min(max(ep, 0), FTC_MAX_EPOCHS)\n        return max(0.20, 0.5 * (1.0 + math.cos(math.pi * x / FTC_MAX_EPOCHS)))\n\n    scheduler = torch.optim.lr_scheduler.LambdaLR(\n        optimizer, lr_lambda=lr_factor\n    )\n    scaler = torch.amp.GradScaler(\"cuda\", enabled=dev.type == \"cuda\")\n\n    stale = 0\n    history = []\n\n    for epoch in range(1, FTC_MAX_EPOCHS + 1):\n        train_loss = train_one_specialist_epoch(\n            model,\n            cache,\n            slot_mask,\n            y,\n            label_mask,\n            train_idx,\n            dev,\n            optimizer,\n            scaler,\n            pos_weight,\n            epoch_seed=SEED + 1000 * mi + epoch,\n            non_specialist_snapshot=non_specialist_snapshot,\n        )\n\n        val_pred = predict_member_frontier(\n            model, cache, slot_mask, val_idx, dev, IMG\n        )\n\n        non_spec_idx = np.asarray(\n            [j for j in range(len(TARGETS)) if j not in set(SPECIALIST_IDX.tolist())],\n            dtype=int,\n        )\n        non_spec_drift = float(\n            np.max(np.abs(val_pred[:, non_spec_idx] - parent_pred[:, non_spec_idx]))\n        )\n        if non_spec_drift > 5e-5:\n            raise RuntimeError(\n                f\"{m['id']}: non-specialist predictions drifted by \"\n                f\"{non_spec_drift:.4g}; specialist isolation contract failed\"\n            )\n\n        val_full_bce = prob_bce(val_pred, y[val_idx], label_mask[val_idx])\n        val_full_auc, _ = macro_auc(val_pred, y[val_idx], label_mask[val_idx])\n        val_spec_bce = prob_bce(\n            val_pred, y[val_idx], label_mask[val_idx], SPECIALIST_IDX\n        )\n        val_spec_auc, _ = macro_auc(\n            val_pred, y[val_idx], label_mask[val_idx], SPECIALIST_IDX\n        )\n\n        accepted = better_specialist_candidate(\n            val_spec_auc,\n            val_spec_bce,\n            val_full_auc,\n            best_spec_auc,\n            best_spec_bce,\n            parent_spec_bce,\n            parent_full_auc,\n        )\n\n        history.append({\n            \"epoch\": epoch,\n            \"train_loss\": train_loss,\n            \"val_specialist_bce\": val_spec_bce,\n            \"val_specialist_auc\": val_spec_auc,\n            \"val_full_bce\": val_full_bce,\n            \"val_full_macro_auc\": val_full_auc,\n            \"accepted_by_gate\": bool(accepted),\n            \"non_specialist_max_drift\": non_spec_drift,\n            \"lr\": optimizer.param_groups[0][\"lr\"],\n        })\n\n        log(\n            f\"  epoch {epoch}: train={train_loss:.5f}, \"\n            f\"spec_bce={val_spec_bce:.5f}, spec_auc={val_spec_auc:.4f}, \"\n            f\"full_auc={val_full_auc:.4f}, \"\n            f\"gate={'ACCEPT' if accepted else 'reject'}\"\n        )\n\n        if accepted:\n            best_spec_bce = val_spec_bce\n            best_spec_auc = val_spec_auc\n            best_full_bce = val_full_bce\n            best_full_auc = val_full_auc\n            best_epoch = epoch\n            best_state = cpu_state_dict(model)\n            best_pred = val_pred.copy()\n            stale = 0\n        else:\n            stale += 1\n\n        scheduler.step()\n\n        if stale >= FTC_PATIENCE:\n            log(\n                f\"  early stop after epoch {epoch}; \"\n                f\"no specialist improvement for {stale} epoch(s)\"\n            )\n            break\n\n    promoted = best_epoch > 0\n\n    if promoted:\n        model.load_state_dict(best_state, strict=True)\n    else:\n        model.load_state_dict(ck[\"model\"], strict=True)\n        best_spec_bce = parent_spec_bce\n        best_spec_auc = parent_spec_auc\n        best_full_bce = parent_full_bce\n        best_full_auc = parent_full_auc\n        best_pred = parent_pred.copy()\n\n    new_fp_seed = int(SEED)\n    new_fp = fingerprint(model, dev, IMG, seed=new_fp_seed).tolist()\n    final_state = cpu_state_dict(model)\n\n    root_id = str(m.get(\"root_base_id\") or m.get(\"id\")).replace(\"_ftb\", \"\")\n    new_id = f\"{root_id}_ftc\"\n    new_file = f\"ftc_{root_id}.pt\"\n\n    new_ck = dict(ck)\n    new_ck[\"model\"] = final_state\n    new_ck[\"fingerprint\"] = new_fp\n    new_ck[\"fingerprint_seed\"] = new_fp_seed\n    new_ck[\"ft_stage\"] = \"FT-C_TARGET_SPECIALIST\"\n    new_ck[\"parent_stage\"] = \"FT-B_HARD_EXAMPLE\"\n    new_ck[\"parent_id\"] = m[\"id\"]\n    new_ck[\"parent_file\"] = m[\"file\"]\n    new_ck[\"root_base_id\"] = root_id\n    new_ck[\"ft_validation_mode\"] = \"NEW_EXPERT_CV_NOT_HISTORICAL_OOF\"\n    new_ck[\"ft_val_fold\"] = val_fold\n    new_ck[\"ft_best_epoch\"] = int(best_epoch)\n    new_ck[\"ft_promoted\"] = bool(promoted)\n    new_ck[\"specialist_targets\"] = SPECIALIST_TARGETS\n    new_ck[\"specialist_parameter_policy\"] = (\n        \"backbone/shared head frozen; only query + out target rows receive specialist loss\"\n    )\n    new_ck[\"ft_parent_specialist_bce\"] = float(parent_spec_bce)\n    new_ck[\"ft_best_specialist_bce\"] = float(best_spec_bce)\n    new_ck[\"ft_parent_specialist_auc\"] = (\n        float(parent_spec_auc) if np.isfinite(parent_spec_auc) else None\n    )\n    new_ck[\"ft_best_specialist_auc\"] = (\n        float(best_spec_auc) if np.isfinite(best_spec_auc) else None\n    )\n    new_ck[\"ft_history\"] = history\n\n    torch.save(new_ck, OUT / new_file)\n\n    nm = dict(m)\n    nm[\"id\"] = new_id\n    nm[\"file\"] = new_file\n    nm[\"ft_stage\"] = \"FT-C_TARGET_SPECIALIST\"\n    nm[\"parent_stage\"] = \"FT-B_HARD_EXAMPLE\"\n    nm[\"parent_id\"] = m[\"id\"]\n    nm[\"parent_file\"] = m[\"file\"]\n    nm[\"root_base_id\"] = root_id\n    nm[\"ft_promoted\"] = bool(promoted)\n    nm[\"ft_best_epoch\"] = int(best_epoch)\n    nm[\"specialist_targets\"] = SPECIALIST_TARGETS\n    nm[\"ft_parent_specialist_bce\"] = float(parent_spec_bce)\n    nm[\"ft_best_specialist_bce\"] = float(best_spec_bce)\n    nm[\"ft_parent_specialist_auc\"] = (\n        float(parent_spec_auc) if np.isfinite(parent_spec_auc) else None\n    )\n    nm[\"ft_best_specialist_auc\"] = (\n        float(best_spec_auc) if np.isfinite(best_spec_auc) else None\n    )\n    new_members.append(nm)\n\n    for local_pos, cache_idx in enumerate(val_idx):\n        uid = studies[int(cache_idx)]\n        g = uid_to_global[uid]\n        oof_ftc_sum[g] += best_pred[local_pos]\n        oof_count[g] += 1\n\n    metrics_rows.append({\n        \"parent_id\": m[\"id\"],\n        \"new_id\": new_id,\n        \"base_fold\": int(m.get(\"fold\")),\n        \"ft_val_fold\": val_fold,\n        \"train_n\": len(train_idx),\n        \"val_n\": len(val_idx),\n        \"parent_specialist_bce\": parent_spec_bce,\n        \"best_specialist_bce\": best_spec_bce,\n        \"delta_specialist_bce\": best_spec_bce - parent_spec_bce,\n        \"parent_specialist_auc\": parent_spec_auc,\n        \"best_specialist_auc\": best_spec_auc,\n        \"delta_specialist_auc\": (\n            best_spec_auc - parent_spec_auc\n            if np.isfinite(best_spec_auc) and np.isfinite(parent_spec_auc)\n            else np.nan\n        ),\n        \"parent_full_auc\": parent_full_auc,\n        \"best_full_auc\": best_full_auc,\n        \"best_epoch\": best_epoch,\n        \"promoted\": promoted,\n        \"parent_oof_maxdiff\": parent_oof_maxdiff,\n        \"parent_fingerprint_seed\": parent_fp_seed,\n        \"new_fingerprint_seed\": new_fp_seed,\n        \"non_specialist_isolation_verified\": True,\n    })\n\n    del model, ck, final_state, best_state\n    gc.collect()\n    if dev.type == \"cuda\":\n        torch.cuda.empty_cache()\n\nmetrics = pd.DataFrame(metrics_rows)\nmetrics.to_csv(OUT / \"ft_c_member_metrics.csv\", index=False)\ndisplay(metrics)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:00:38.712577Z","iopub.execute_input":"2026-08-11T21:00:38.712937Z"},"trusted":true},"outputs":[],"execution_count":null},{"id":"f139409b","cell_type":"markdown","source":"## 7. OOF comparison and Stage-4 handoff","metadata":{}},{"id":"9fbd021a","cell_type":"code","source":"if \"metrics\" not in globals():\n    raise RuntimeError(\n        \"FT-C training loop did not finish, so metrics are unavailable. \"\n        \"Scroll to the first error above; do not run the summary cell independently.\"\n    )\nif len(new_members) != len(members):\n    raise RuntimeError(\n        f\"FT-C produced {len(new_members)}/{len(members)} members. \"\n        \"Training is incomplete; summary/submission handoff is intentionally blocked.\"\n    )\n\nvalid = oof_count > 0\nif not valid.all():\n    print(\"WARNING: missing FT-C OOF rows:\", int((~valid).sum()))\n\nftc_oof = np.full_like(oof_ftc_sum, np.nan)\nftc_oof[valid] = oof_ftc_sum[valid] / oof_count[valid, None]\n\nbase_oof = np.column_stack([oof3[f\"base__{t}\"].to_numpy(float) for t in TARGETS])\nfta_oof = np.column_stack([oof3[f\"fta__{t}\"].to_numpy(float) for t in TARGETS])\nftb_oof = np.column_stack([oof3[f\"ftb__{t}\"].to_numpy(float) for t in TARGETS])\n\noof_frame = expert[[\"StudyInstanceUID\", \"ft_fold\", *TARGETS]].copy()\noof_frame[\"n_ftc_votes\"] = oof_count\n\nfor j, t in enumerate(TARGETS):\n    oof_frame[f\"base__{t}\"] = base_oof[:, j]\n    oof_frame[f\"fta__{t}\"] = fta_oof[:, j]\n    oof_frame[f\"ftb__{t}\"] = ftb_oof[:, j]\n    oof_frame[f\"ftc__{t}\"] = ftc_oof[:, j]\n\noof_frame.to_csv(OUT / \"expert_cv_predictions_stage4.csv\", index=False)\n\ny_all = expert[TARGETS].to_numpy(np.float32)\nmask_all = np.isfinite(y_all).astype(np.float32)\ny_safe = np.nan_to_num(y_all, nan=0.0)\n\ndef branch_metrics(name, pred):\n    bce = prob_bce(pred[valid], y_safe[valid], mask_all[valid])\n    auc, per = macro_auc(pred[valid], y_safe[valid], mask_all[valid])\n    spec_bce = prob_bce(\n        pred[valid], y_safe[valid], mask_all[valid], SPECIALIST_IDX\n    )\n    spec_auc, _ = macro_auc(\n        pred[valid], y_safe[valid], mask_all[valid], SPECIALIST_IDX\n    )\n    return name, bce, auc, spec_bce, spec_auc, per\n\nbranches = [\n    branch_metrics(\"BASE\", base_oof),\n    branch_metrics(\"FT-A\", fta_oof),\n    branch_metrics(\"FT-B\", ftb_oof),\n    branch_metrics(\"FT-C\", ftc_oof),\n]\n\nsummary = pd.DataFrame([\n    {\n        \"branch\": name,\n        \"expert_cv_bce\": bce,\n        \"expert_cv_macro_auc\": auc,\n        \"structural_specialist_bce\": sbce,\n        \"structural_specialist_macro_auc\": sauc,\n    }\n    for name, bce, auc, sbce, sauc, _ in branches\n]).sort_values(\"expert_cv_macro_auc\", ascending=False)\n\nsummary.to_csv(OUT / \"expert_cv_branch_summary_stage4.csv\", index=False)\ndisplay(summary)\n\nper_target = pd.DataFrame({\"target\": TARGETS})\nfor name, _, _, _, _, per in branches:\n    per_target[f\"{name.lower().replace('-', '')}_auc\"] = [per.get(t, np.nan) for t in TARGETS]\n\nper_target[\"ftc_minus_ftb\"] = per_target[\"ftc_auc\"] - per_target[\"ftb_auc\"]\nper_target[\"ftc_minus_base\"] = per_target[\"ftc_auc\"] - per_target[\"base_auc\"]\nper_target[\"is_specialist_target\"] = per_target[\"target\"].isin(SPECIALIST_TARGETS)\nper_target.to_csv(OUT / \"expert_cv_target_auc_stage4.csv\", index=False)\ndisplay(per_target)\n\nhistory = stage3_manifest.get(\"history\")\nif not isinstance(history, list):\n    history = [] if history is None else [history]\n\nstage4_history = history + [{\n    \"stage\": \"FT-C_TARGET_SPECIALIST\",\n    \"seed\": SEED,\n    \"fingerprint_seed\": SEED,\n    \"specialist_targets\": SPECIALIST_TARGETS,\n    \"parameter_policy\": \"backbone/shared head frozen; target-specific query/out only\",\n    \"max_epochs\": FTC_MAX_EPOCHS,\n    \"head_lr\": FTC_HEAD_LR,\n    \"n_output_members\": len(new_members),\n    \"expert_n\": len(expert),\n    \"validation_mode\": \"NEW_EXPERT_CV_NOT_HISTORICAL_OOF\",\n}]\n\nnew_manifest = {\n    \"format\": stage3_manifest.get(\"format\"),\n    \"targets\": TARGETS,\n    \"history\": stage4_history,\n    \"members\": new_members,\n}\n(OUT / \"manifest.json\").write_text(json.dumps(new_manifest, indent=2))\n\nbest_single = str(\n    summary.sort_values(\n        [\"expert_cv_macro_auc\", \"expert_cv_bce\"],\n        ascending=[False, True],\n    ).iloc[0][\"branch\"]\n)\n\nstatus4 = {\n    \"stage4_ok\": len(new_members) == len(members) and len(new_members) > 0,\n    \"stage\": \"FT-C_TARGET_SPECIALIST\",\n    \"fingerprint_seed\": int(SEED),\n    \"n_input_members\": len(members),\n    \"n_output_members\": len(new_members),\n    \"n_promoted\": int(metrics[\"promoted\"].sum()) if len(metrics) else 0,\n    \"n_rolled_back_to_ftb\": int((~metrics[\"promoted\"]).sum()) if len(metrics) else 0,\n    \"specialist_targets\": SPECIALIST_TARGETS,\n    \"validation_mode\": \"NEW_EXPERT_CV_NOT_HISTORICAL_OOF\",\n    \"best_single_cv_branch_by_macro_auc\": best_single,\n    \"submission_file_policy\": (\n        \"No interim submission file. Notebook 05 will write exactly \"\n        \"/kaggle/working/submission.csv.\"\n    ),\n    \"next_notebook\": \"05_final_ensemble_and_submission.ipynb\",\n}\n(OUT / \"stage4_status.json\").write_text(json.dumps(status4, indent=2))\n\nprint(json.dumps(status4, indent=2))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"id":"017bcd70","cell_type":"markdown","source":"## 8. Output inventory","metadata":{}},{"id":"9af0ddca","cell_type":"code","source":"print(\"Stage 4 output:\")\ntotal_bytes = 0\nfor p in sorted(OUT.iterdir()):\n    if p.is_file():\n        total_bytes += p.stat().st_size\n        print(f\" - {p.name:44s} {p.stat().st_size / (1024**2):9.2f} MB\")\n\nprint(f\"Total output size: {total_bytes / (1024**3):.3f} GB\")\nprint()\nprint(\"IMPORTANT: no submission.csv is created in Stage 4.\")\nprint(\"Next: add this Notebook 04 output to Notebook 05.\")\nprint(\"Notebook 05 will select the final OOF blend and write exactly:\")\nprint(\"/kaggle/working/submission.csv\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"id":"cf2bdcef","cell_type":"markdown","source":"## What to send back\n\nAfter Notebook 04 finishes, send:\n\n- the Output screenshot; and\n- the saved Notebook 04 with outputs.\n\nThe most important files are:\n\n- `stage4_status.json`\n- `expert_cv_branch_summary_stage4.csv`\n- `expert_cv_target_auc_stage4.csv`\n- `ft_c_member_metrics.csv`\n\nNotebook 05 can then be made final and result-driven instead of guessing the FT-C blend weight.","metadata":{}}]}