{"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":341772948,"sourceType":"kernelVersion"},{"sourceId":341776840,"sourceType":"kernelVersion"},{"sourceId":341785614,"sourceType":"kernelVersion"},{"sourceId":341421415,"sourceType":"kernelVersion"},{"sourceId":4533,"sourceType":"modelInstanceVersion"}],"isGpuEnabled":false,"isInternetEnabled":true,"language":"python","sourceType":"notebook"},"papermill":{"default_parameters":{},"duration":131.976432,"end_time":"2026-08-11T21:03:32.839657+00:00","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2026-08-11T21:01:20.863225+00:00","version":"2.7.0"},"widgets":{"application/vnd.jupyter.widget-state+json":{"state":{"019819626cb84e1e9b66c55c3d1c7076":{"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_394af389da27448c8865554798451a70","placeholder":"​","style":"IPY_MODEL_ff9282cd5cd34c709ac5b508d00e3853","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 982.61it/s, Materializing param=layernorm.weight]"}},"059b64b58836489b963ffcfe814a5ac9":{"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}},"0c67cd5d99bf465b892730d3af3b97d8":{"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}},"154ae3d72d0e4f60bcd4297096773ad8":{"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":""}},"1b8403ba32834eeeb920c19325a84886":{"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}},"1ddb21d5f7de49d19463092270f83f81":{"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_77d33627f38b444298e3f527fc86aa6d","placeholder":"​","style":"IPY_MODEL_79e25fe0b890425d9aa592b19d0af3ed","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 1065.30it/s, Materializing param=layernorm.weight]"}},"22bc899880b748db8d40400342e1de49":{"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}},"238b52bbbea04ceb8dc7d4b860899877":{"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}},"300a42958a924cec8aa98464438e265e":{"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_1b8403ba32834eeeb920c19325a84886","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_95807a97779c4eb88e830094527a99a5","tabbable":null,"tooltip":null,"value":223}},"394af389da27448c8865554798451a70":{"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}},"3d326b190a324b48bbceb5afbf0f026d":{"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_a65b317ac82e4555818a7875a6279387","IPY_MODEL_300a42958a924cec8aa98464438e265e","IPY_MODEL_019819626cb84e1e9b66c55c3d1c7076"],"layout":"IPY_MODEL_68ef5fbd4a9544f6b42a02b5527b35eb","tabbable":null,"tooltip":null}},"3d64448d04f1444587f672224e0deccd":{"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":""}},"4232939e91e14b4a8a291dc2bf62d933":{"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}},"46101b60b81b479f8be14ef276b3be6a":{"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}},"4952dc175b4e4a4395d198c8e1dccad8":{"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}},"4ae2850978a0449ab137874903385a62":{"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}},"4afd8d20b5954455a4d48a3619cc9a14":{"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}},"4ca849f960434a51bac803e6159b93b7":{"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}},"54e16b696f644a1aa6d6e43f4f77e959":{"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}},"5fded0b1013448b6921bdda23a9cb784":{"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":""}},"682639114c5c42f0ae2f257813710ce0":{"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}},"68ef5fbd4a9544f6b42a02b5527b35eb":{"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}},"68f63037a83e4b6b819170d50a161c2e":{"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_eee23a75ded94f6da5598d93217b50c0","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_5fded0b1013448b6921bdda23a9cb784","tabbable":null,"tooltip":null,"value":223}},"69fb4e375a4c4cd4834bd996622bad09":{"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}},"77d33627f38b444298e3f527fc86aa6d":{"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}},"78736b4df39946bb99ca0f70b8950c1d":{"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_f1080609a92145e6ae802133559a7de5","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_3d64448d04f1444587f672224e0deccd","tabbable":null,"tooltip":null,"value":223}},"79e25fe0b890425d9aa592b19d0af3ed":{"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}},"7c27ecd34a3b41c6b9bb1803a36e5a98":{"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_d579f9553a80456d9ff02803624241be","IPY_MODEL_86b0340f0e064e4dbd26a5194cfa68f0","IPY_MODEL_1ddb21d5f7de49d19463092270f83f81"],"layout":"IPY_MODEL_94e6b112c2484cd99b0a3758560c7f7a","tabbable":null,"tooltip":null}},"7d83de32f99e47f5b3a1b09b84234915":{"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_bca452e65b4848c0918eef8badaef8b1","placeholder":"​","style":"IPY_MODEL_4ca849f960434a51bac803e6159b93b7","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 894.28it/s, Materializing param=layernorm.weight]"}},"86b0340f0e064e4dbd26a5194cfa68f0":{"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_059b64b58836489b963ffcfe814a5ac9","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_b018a1d4d5e94501b2aa3d5cd8e6d261","tabbable":null,"tooltip":null,"value":223}},"94e6b112c2484cd99b0a3758560c7f7a":{"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}},"95807a97779c4eb88e830094527a99a5":{"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":""}},"95977bdc2df34f43869131ef560d2757":{"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}},"9813be6cc1b24155b6936b4625680893":{"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_682639114c5c42f0ae2f257813710ce0","placeholder":"​","style":"IPY_MODEL_bbf080add4654719ae07577871bef833","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"9ac78108e1194e05acdde479487bad08":{"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_a708c5ae0ae045339b0854fd50f47e4a","placeholder":"​","style":"IPY_MODEL_f82c32d264ad448581a11d8d26caa25c","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"a303705088bd4ae98d99c648a166a1c8":{"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}},"a4ff1d41e82e40b698547cbb39a3ee9f":{"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_4952dc175b4e4a4395d198c8e1dccad8","placeholder":"​","style":"IPY_MODEL_46101b60b81b479f8be14ef276b3be6a","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 954.03it/s, Materializing param=layernorm.weight]"}},"a65b317ac82e4555818a7875a6279387":{"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_95977bdc2df34f43869131ef560d2757","placeholder":"​","style":"IPY_MODEL_bcb3da1d1f0e43b1b636f8217e1850da","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"a708c5ae0ae045339b0854fd50f47e4a":{"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}},"b018a1d4d5e94501b2aa3d5cd8e6d261":{"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":""}},"b5de1906359a4111be22622d28d76132":{"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_9ac78108e1194e05acdde479487bad08","IPY_MODEL_e1d45a463a69471d8f4105734c530301","IPY_MODEL_a4ff1d41e82e40b698547cbb39a3ee9f"],"layout":"IPY_MODEL_a303705088bd4ae98d99c648a166a1c8","tabbable":null,"tooltip":null}},"bbf080add4654719ae07577871bef833":{"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}},"bca452e65b4848c0918eef8badaef8b1":{"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}},"bcb3da1d1f0e43b1b636f8217e1850da":{"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}},"bf9bdf30f2174b71addd2c831a9ec40b":{"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_22bc899880b748db8d40400342e1de49","placeholder":"​","style":"IPY_MODEL_0c67cd5d99bf465b892730d3af3b97d8","tabbable":null,"tooltip":null,"value":" 223/223 [00:00&lt;00:00, 987.32it/s, Materializing param=layernorm.weight]"}},"d1e8d110e99f441ca83ff9fdf006256c":{"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}},"d579f9553a80456d9ff02803624241be":{"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_d1e8d110e99f441ca83ff9fdf006256c","placeholder":"​","style":"IPY_MODEL_238b52bbbea04ceb8dc7d4b860899877","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"dc11a0399a92480eb383377242165e77":{"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_ecfaf54a90064839a186877e44c05b49","IPY_MODEL_78736b4df39946bb99ca0f70b8950c1d","IPY_MODEL_7d83de32f99e47f5b3a1b09b84234915"],"layout":"IPY_MODEL_4232939e91e14b4a8a291dc2bf62d933","tabbable":null,"tooltip":null}},"e1d45a463a69471d8f4105734c530301":{"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_4ae2850978a0449ab137874903385a62","max":223,"min":0,"orientation":"horizontal","style":"IPY_MODEL_154ae3d72d0e4f60bcd4297096773ad8","tabbable":null,"tooltip":null,"value":223}},"ecfaf54a90064839a186877e44c05b49":{"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_4afd8d20b5954455a4d48a3619cc9a14","placeholder":"​","style":"IPY_MODEL_69fb4e375a4c4cd4834bd996622bad09","tabbable":null,"tooltip":null,"value":"Loading weights: 100%"}},"eee23a75ded94f6da5598d93217b50c0":{"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}},"f1080609a92145e6ae802133559a7de5":{"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}},"f82c32d264ad448581a11d8d26caa25c":{"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}},"faf4b2ef0d3c4776b8204b41d6b5e91e":{"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_9813be6cc1b24155b6936b4625680893","IPY_MODEL_68f63037a83e4b6b819170d50a161c2e","IPY_MODEL_bf9bdf30f2174b71addd2c831a9ec40b"],"layout":"IPY_MODEL_54e16b696f644a1aa6d6e43f4f77e959","tabbable":null,"tooltip":null}},"ff9282cd5cd34c709ac5b508d00e3853":{"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}}},"version_major":2,"version_minor":0}}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# RSNA Knee — Notebook 05 FINAL: OOF-Selected Ensemble + Submission\n\nThis is the **final notebook**.\n\nIt does **no more training**. It uses:\n\n1. the original 20-member DINO ensemble as the safety/base family;\n2. Notebook 04 output for expert-CV evidence and the 5 FT-C checkpoints;\n3. a conservative nested target-wise selector to decide whether any FT-C contribution\n   is stable enough to blend with BASE;\n4. final hidden-test inference;\n5. exactly one competition file:\n\n`/kaggle/working/submission.csv`\n\n### Why BASE remains the anchor\n\nNotebook 04 reported:\n\n- BASE macro AUC: ~0.97897\n- FT-A macro AUC: ~0.97237\n- FT-B macro AUC: ~0.97204\n- FT-C macro AUC: ~0.97204\n- FT-C promoted: 0 / 5 (all five rolled back to FT-B)\n\nSo this notebook never blindly replaces BASE. A fine-tuned contribution is used only\nfor targets where a nested fold-wise blend shows a stable OOF ranking gain.","metadata":{}},{"cell_type":"markdown","source":"## Fixed V2 — final inference metadata contract repaired\n\nThe failed run stopped at `pick_slots()` with `KeyError: 'fatsat'`.\n\n`walk_selected()` returns raw DICOM header rows. The successful pipeline always\npasses those rows through `annotate(...)`, which creates the derived `fatsat`,\n`fluid`, `weight`, and `px` columns required by the slot selector.\n\nThis version restores that exact preprocessing contract and adds preflight checks\nso the same failure cannot silently recur.","metadata":{}},{"cell_type":"markdown","source":"## Required Kaggle inputs\n\nAttach **only these four inputs**:\n\n1. **RSNA Knee Abnormality Detection** competition\n2. **DINO v2 — dinov2-small**\n3. **RSNA Knee weights** — the original package containing the 20 base checkpoints\n4. **Notebook 04: Target-Specialist Fine-Tuning** output (`rsna_stage4_ftc`)\n\nYou do **not** need Notebook 01, 02, or 03 as separate inputs.","metadata":{}},{"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 hashlib\nimport json\nimport math\nimport re\nimport time\nimport traceback\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 = 2026\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# Final inference controls.\nEVAL_BATCH = int(os.environ.get(\"FINAL_EVAL_BATCH\", \"8\"))\nTIME_BUDGET = float(os.environ.get(\"FINAL_TIME_BUDGET_HOURS\", \"8\")) * 3600\nMIN_WINDOWS = int(os.environ.get(\"FINAL_MIN_WINDOWS\", \"3\"))\n\n# Conservative nested blend selector.\nALPHA_GRID = np.asarray([0.0, 0.10, 0.20, 0.30, 0.40, 0.50], dtype=float)\nMETA_MIN_AUC_GAIN = float(os.environ.get(\"META_MIN_AUC_GAIN\", \"0.002\"))\nFULL_MIN_AUC_GAIN = float(os.environ.get(\"FULL_MIN_AUC_GAIN\", \"0.002\"))\nMIN_NONZERO_OUTER_CHOICES = int(os.environ.get(\"MIN_NONZERO_OUTER_CHOICES\", \"3\"))\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\nFINAL_PATH = Path(\"/kaggle/working/submission.csv\")\nDIAG_DIR = Path(\"/kaggle/working/final_diagnostics\")\nDIAG_DIR.mkdir(parents=True, exist_ok=True)\n\n# Never leave a stale submission from an earlier failed interactive run.\nif FINAL_PATH.exists():\n    FINAL_PATH.unlink()\n","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:51.433525Z","iopub.execute_input":"2026-08-11T21:20:51.433992Z","iopub.status.idle":"2026-08-11T21:20:51.451068Z","shell.execute_reply.started":"2026-08-11T21:20:51.433961Z","shell.execute_reply":"2026-08-11T21:20:51.450367Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 1. Discover and validate the four required inputs","metadata":{}},{"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_root():\n    candidates = [\n        Path(\"/kaggle/input/competitions/rsna-knee-abnormality-detection\"),\n        Path(\"/kaggle/input/rsna-knee-abnormality-detection\"),\n    ]\n    for c in candidates:\n        if (c / \"test.csv\").is_file() and (c / \"test_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            p = Path(root)\n            if (p / \"test.csv\").is_file() and (p / \"test_series\").is_dir():\n                return p\n    raise FileNotFoundError(\"RSNA Knee competition mount not found\")\n\n\ndef _looks_like_dinov2_config(config_path):\n    try:\n        cfg = json.loads(Path(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():\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 (preferred / \"config.json\").is_file():\n        return preferred\n\n    base = Path(\"/kaggle/input\")\n    hits = []\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\" in files and _looks_like_dinov2_config(Path(root) / \"config.json\"):\n                hits.append(Path(root))\n\n    for p in hits:\n        try:\n            cfg = json.loads((p / \"config.json\").read_text())\n            if int(cfg.get(\"hidden_size\", -1)) == 384:\n                return p\n        except Exception:\n            pass\n    return hits[0] if hits else None\n\n\ndef _manifest_complete(root):\n    root = Path(root)\n    mp = root / \"manifest.json\"\n    if not mp.is_file():\n        return None\n    try:\n        man = json.loads(mp.read_text())\n    except Exception:\n        return None\n    members = man.get(\"members\")\n    if not isinstance(members, list) or not members:\n        return None\n    if any(not (root / str(m.get(\"file\"))).is_file() for m in members):\n        return None\n    return man\n\n\ndef find_stage4():\n    explicit = os.environ.get(\"STAGE4_DIR\", \"\").strip()\n    if explicit:\n        p = Path(explicit)\n        st = json.loads((p / \"stage4_status.json\").read_text())\n        man = _manifest_complete(p)\n        if st.get(\"stage4_ok\") and st.get(\"stage\") == \"FT-C_TARGET_SPECIALIST\" and man:\n            return p, st, man\n        raise FileNotFoundError(f\"STAGE4_DIR={explicit!r} is not a complete Stage-4 package\")\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            if \"stage4_status.json\" not in files:\n                continue\n            p = Path(root)\n            try:\n                st = json.loads((p / \"stage4_status.json\").read_text())\n            except Exception:\n                continue\n            man = _manifest_complete(p)\n            if st.get(\"stage4_ok\") and st.get(\"stage\") == \"FT-C_TARGET_SPECIALIST\" and man:\n                return p, st, man\n    raise FileNotFoundError(\"Notebook 04 output (rsna_stage4_ftc) not found\")\n\n\ndef find_base_weights(stage4_path):\n    explicit = os.environ.get(\"KNEE_WEIGHTS_DIR\", \"\").strip()\n    candidates = []\n    if explicit:\n        candidates.append(Path(explicit))\n    candidates.append(Path(\"/kaggle/input/rsna-knee-weights\"))\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            if \"manifest.json\" in files:\n                candidates.append(Path(root))\n\n    seen = set()\n    for p in candidates:\n        key = str(p)\n        if key in seen or p == stage4_path:\n            continue\n        seen.add(key)\n        man = _manifest_complete(p)\n        if man is None:\n            continue\n\n        # The original safety family is the 20-member package.\n        if len(man.get(\"members\", [])) >= 10:\n            return p, man\n\n    raise FileNotFoundError(\n        \"Original RSNA Knee weights package not found. \"\n        \"Attach the 'RSNA Knee weights' dataset containing the 20 base checkpoints.\"\n    )\n\n\nROOT = find_root()\nDINO = find_dinov2()\nSTAGE4, STAGE4_STATUS, STAGE4_MANIFEST = find_stage4()\nBASE_WEIGHTS, BASE_MANIFEST = find_base_weights(STAGE4)\n\nif DINO is None:\n    raise FileNotFoundError(\"DINOv2-small model input not found\")\n\nlog(f\"competition: {ROOT}\")\nlog(f\"DINOv2-small: {DINO}\")\nlog(f\"original base weights: {BASE_WEIGHTS} ({len(BASE_MANIFEST['members'])} members)\")\nlog(f\"Stage 4: {STAGE4} ({len(STAGE4_MANIFEST['members'])} members)\")\n\nif len(BASE_MANIFEST[\"members\"]) != 20:\n    print(\n        \"WARNING: expected 20 original base members, found\",\n        len(BASE_MANIFEST[\"members\"]),\n        \"- continuing because the package is complete.\"\n    )\n\ndisplay(pd.DataFrame([{\n    \"stage4_ok\": STAGE4_STATUS.get(\"stage4_ok\"),\n    \"stage4_promoted\": STAGE4_STATUS.get(\"n_promoted\"),\n    \"stage4_rollback\": STAGE4_STATUS.get(\"n_rolled_back_to_ftb\"),\n    \"stage4_best_single\": STAGE4_STATUS.get(\"best_single_cv_branch_by_macro_auc\"),\n}]))","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:51.452515Z","iopub.execute_input":"2026-08-11T21:20:51.453233Z","iopub.status.idle":"2026-08-11T21:20:52.410557Z","shell.execute_reply.started":"2026-08-11T21:20:51.453199Z","shell.execute_reply":"2026-08-11T21:20:52.409916Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2. Nested OOF selector — BASE remains default","metadata":{}},{"cell_type":"code","source":"oof_path = STAGE4 / \"expert_cv_predictions_stage4.csv\"\nsummary_path = STAGE4 / \"expert_cv_branch_summary_stage4.csv\"\n\noof = pd.read_csv(oof_path, dtype={\"StudyInstanceUID\": str})\nbranch_summary = pd.read_csv(summary_path)\n\nrequired = {\"StudyInstanceUID\", \"ft_fold\", *TARGETS}\nfor t in TARGETS:\n    required.add(f\"base__{t}\")\n    required.add(f\"ftc__{t}\")\nmissing = required.difference(oof.columns)\nif missing:\n    raise RuntimeError(f\"Stage-4 OOF is missing columns: {sorted(missing)}\")\n\ndisplay(branch_summary)\n\n\ndef pct_rank_1d(x):\n    return pd.Series(np.asarray(x, float)).rank(\n        method=\"average\", pct=True\n    ).to_numpy(np.float64)\n\n\ndef safe_auc(y, p):\n    y = np.asarray(y, float)\n    p = np.asarray(p, float)\n    good = np.isfinite(y) & np.isfinite(p)\n    y, p = y[good], p[good]\n    if len(y) < 2 or len(np.unique(y)) < 2:\n        return np.nan\n    return float(roc_auc_score(y, p))\n\n\ndef select_target_alpha(y, fold, base_prob, ftc_prob):\n    # Rank features are built without labels. This mirrors the final test-space rank blend.\n    rb = pct_rank_1d(base_prob)\n    rf = pct_rank_1d(ftc_prob)\n    folds = sorted(pd.Series(fold).dropna().astype(int).unique().tolist())\n\n    meta_pred = np.full(len(y), np.nan, dtype=float)\n    outer_choices = []\n\n    for outer in folds:\n        tr = np.asarray(fold) != outer\n        va = np.asarray(fold) == outer\n\n        train_scores = []\n        for a in ALPHA_GRID:\n            p = (1.0 - a) * rb[tr] + a * rf[tr]\n            train_scores.append(safe_auc(np.asarray(y)[tr], p))\n\n        # Highest train-fold AUC; ties always choose the smaller FT-C weight.\n        finite = np.asarray([\n            s if np.isfinite(s) else -np.inf for s in train_scores\n        ])\n        best_i = int(np.argmax(finite))\n        a = float(ALPHA_GRID[best_i])\n        outer_choices.append(a)\n        meta_pred[va] = (1.0 - a) * rb[va] + a * rf[va]\n\n    base_auc = safe_auc(y, rb)\n    ftc_auc = safe_auc(y, rf)\n    meta_auc = safe_auc(y, meta_pred)\n\n    full_scores = []\n    for a in ALPHA_GRID:\n        full_scores.append(safe_auc(y, (1.0 - a) * rb + a * rf))\n    finite_full = np.asarray([\n        s if np.isfinite(s) else -np.inf for s in full_scores\n    ])\n    full_best_i = int(np.argmax(finite_full))\n    full_best_alpha = float(ALPHA_GRID[full_best_i])\n    full_best_auc = float(finite_full[full_best_i])\n\n    nonzero = int(sum(a > 0 for a in outer_choices))\n    median_alpha = float(np.median(outer_choices))\n    # Snap the median back to our safe grid, preferring the nearest smaller alpha on ties.\n    final_alpha = float(\n        ALPHA_GRID[np.argmin(np.abs(ALPHA_GRID - median_alpha))]\n    )\n\n    meta_gain = meta_auc - base_auc if np.isfinite(meta_auc) and np.isfinite(base_auc) else -np.inf\n    full_gain = full_best_auc - base_auc if np.isfinite(base_auc) else -np.inf\n\n    promoted = (\n        final_alpha > 0\n        and nonzero >= MIN_NONZERO_OUTER_CHOICES\n        and meta_gain >= META_MIN_AUC_GAIN\n        and full_gain >= FULL_MIN_AUC_GAIN\n    )\n\n    if not promoted:\n        final_alpha = 0.0\n\n    return {\n        \"base_auc\": base_auc,\n        \"ftc_auc\": ftc_auc,\n        \"nested_meta_auc\": meta_auc,\n        \"nested_meta_gain\": meta_gain,\n        \"full_best_alpha\": full_best_alpha,\n        \"full_best_auc\": full_best_auc,\n        \"full_best_gain\": full_gain,\n        \"outer_choices\": outer_choices,\n        \"nonzero_outer_choices\": nonzero,\n        \"final_alpha\": final_alpha,\n        \"promoted\": bool(promoted),\n    }\n\n\nselection_rows = []\nFINAL_ALPHAS = {}\n\nfold = oof[\"ft_fold\"].to_numpy(int)\n\nfor t in TARGETS:\n    y = oof[t].to_numpy(float)\n    res = select_target_alpha(\n        y,\n        fold,\n        oof[f\"base__{t}\"].to_numpy(float),\n        oof[f\"ftc__{t}\"].to_numpy(float),\n    )\n    FINAL_ALPHAS[t] = float(res[\"final_alpha\"])\n    selection_rows.append({\n        \"target\": t,\n        \"base_auc\": res[\"base_auc\"],\n        \"ftc_auc\": res[\"ftc_auc\"],\n        \"nested_meta_auc\": res[\"nested_meta_auc\"],\n        \"nested_meta_gain\": res[\"nested_meta_gain\"],\n        \"full_best_alpha\": res[\"full_best_alpha\"],\n        \"full_best_auc\": res[\"full_best_auc\"],\n        \"full_best_gain\": res[\"full_best_gain\"],\n        \"outer_choices\": json.dumps(res[\"outer_choices\"]),\n        \"nonzero_outer_choices\": res[\"nonzero_outer_choices\"],\n        \"final_alpha\": res[\"final_alpha\"],\n        \"promoted\": res[\"promoted\"],\n    })\n\nselection = pd.DataFrame(selection_rows)\nselection.to_csv(DIAG_DIR / \"oof_blend_selection.csv\", index=False)\n\nprint(\"Final target-wise FT-C weights:\")\ndisplay(selection)\n\nprint(json.dumps(FINAL_ALPHAS, indent=2))\n\n(DIAG_DIR / \"final_blend_config.json\").write_text(json.dumps({\n    \"method\": \"nested expert-CV conservative BASE-to-FT-C rank blend\",\n    \"alpha_grid\": ALPHA_GRID.tolist(),\n    \"meta_min_auc_gain\": META_MIN_AUC_GAIN,\n    \"full_min_auc_gain\": FULL_MIN_AUC_GAIN,\n    \"min_nonzero_outer_choices\": MIN_NONZERO_OUTER_CHOICES,\n    \"alphas\": FINAL_ALPHAS,\n    \"base_is_default\": True,\n}, indent=2))\n\nNEED_FTC = any(a > 0 for a in FINAL_ALPHAS.values())\nprint(\"Need FT-C hidden-test inference:\", NEED_FTC)\nif not NEED_FTC:\n    print(\"No target cleared the conservative gate: final hidden-test inference will use BASE only.\")","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:52.411984Z","iopub.execute_input":"2026-08-11T21:20:52.412256Z","iopub.status.idle":"2026-08-11T21:20:53.120501Z","shell.execute_reply.started":"2026-08-11T21:20:52.412233Z","shell.execute_reply":"2026-08-11T21:20:53.119657Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3. Checkpoint pixel/preprocessing contract","metadata":{}},{"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)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:53.121461Z","iopub.execute_input":"2026-08-11T21:20:53.121708Z","iopub.status.idle":"2026-08-11T21:20:53.128891Z","shell.execute_reply.started":"2026-08-11T21:20:53.121686Z","shell.execute_reply":"2026-08-11T21:20:53.128377Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4. Exact DICOM preprocessing used by the successful pipeline","metadata":{}},{"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-11T21:20:53.130521Z","iopub.execute_input":"2026-08-11T21:20:53.1308Z","iopub.status.idle":"2026-08-11T21:20:53.154302Z","shell.execute_reply.started":"2026-08-11T21:20:53.13078Z","shell.execute_reply":"2026-08-11T21:20:53.15361Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.155126Z","iopub.execute_input":"2026-08-11T21:20:53.155447Z","iopub.status.idle":"2026-08-11T21:20:53.17024Z","shell.execute_reply.started":"2026-08-11T21:20:53.1554Z","shell.execute_reply":"2026-08-11T21:20:53.169384Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.171164Z","iopub.execute_input":"2026-08-11T21:20:53.171528Z","iopub.status.idle":"2026-08-11T21:20:53.1829Z","shell.execute_reply.started":"2026-08-11T21:20:53.171497Z","shell.execute_reply":"2026-08-11T21:20:53.18214Z"},"trusted":true},"outputs":[],"execution_count":null},{"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    required_meta = {\n        \"StudyInstanceUID\", \"SeriesInstanceUID\", \"n_slices\",\n        \"fatsat\", \"fluid\", \"px\",\n    }\n    missing_meta = required_meta.difference(series_df.columns)\n    if missing_meta:\n        raise RuntimeError(\n            \"pick_slots received raw/unannotated series metadata; missing derived \"\n            f\"columns: {sorted(missing_meta)}. Run annotate(...) before pick_slots.\"\n        )\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-11T21:20:53.183957Z","iopub.execute_input":"2026-08-11T21:20:53.184221Z","iopub.status.idle":"2026-08-11T21:20:53.200152Z","shell.execute_reply.started":"2026-08-11T21:20:53.184201Z","shell.execute_reply":"2026-08-11T21:20:53.19957Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.20113Z","iopub.execute_input":"2026-08-11T21:20:53.2014Z","iopub.status.idle":"2026-08-11T21:20:53.227952Z","shell.execute_reply.started":"2026-08-11T21:20:53.20136Z","shell.execute_reply":"2026-08-11T21:20:53.227218Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.228786Z","iopub.execute_input":"2026-08-11T21:20:53.229056Z","iopub.status.idle":"2026-08-11T21:20:53.257736Z","shell.execute_reply.started":"2026-08-11T21:20:53.229028Z","shell.execute_reply":"2026-08-11T21:20:53.256976Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.259895Z","iopub.execute_input":"2026-08-11T21:20:53.260166Z","iopub.status.idle":"2026-08-11T21:20:53.276447Z","shell.execute_reply.started":"2026-08-11T21:20:53.260136Z","shell.execute_reply":"2026-08-11T21:20:53.275896Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.277603Z","iopub.execute_input":"2026-08-11T21:20:53.278023Z","iopub.status.idle":"2026-08-11T21:20:53.293441Z","shell.execute_reply.started":"2026-08-11T21:20:53.27796Z","shell.execute_reply":"2026-08-11T21:20:53.292702Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.294349Z","iopub.execute_input":"2026-08-11T21:20:53.294643Z","iopub.status.idle":"2026-08-11T21:20:53.31114Z","shell.execute_reply.started":"2026-08-11T21:20:53.294621Z","shell.execute_reply":"2026-08-11T21:20:53.310265Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.31201Z","iopub.execute_input":"2026-08-11T21:20:53.312307Z","iopub.status.idle":"2026-08-11T21:20:53.323007Z","shell.execute_reply.started":"2026-08-11T21:20:53.31228Z","shell.execute_reply":"2026-08-11T21:20:53.322264Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-11T21:20:53.3238Z","iopub.execute_input":"2026-08-11T21:20:53.324083Z","iopub.status.idle":"2026-08-11T21:20:53.337075Z","shell.execute_reply.started":"2026-08-11T21:20:53.324064Z","shell.execute_reply":"2026-08-11T21:20:53.336272Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 5. Final test metadata and package preflight","metadata":{}},{"cell_type":"code","source":"test_df = pd.read_csv(ROOT / \"test.csv\", dtype={\"StudyInstanceUID\": str})\ntest_series = pd.read_csv(\n    ROOT / \"test_series.csv\",\n    dtype={\"StudyInstanceUID\": str, \"SeriesInstanceUID\": str},\n)\n\nif \"StudyInstanceUID\" not in test_df.columns:\n    raise RuntimeError(\"test.csv has no StudyInstanceUID\")\n\ntest_ids = test_df[\"StudyInstanceUID\"].astype(str).tolist()\nif len(test_ids) != len(set(test_ids)):\n    raise RuntimeError(\"test.csv contains duplicate StudyInstanceUID\")\n\nplane_map = dict(zip(\n    test_series[\"SeriesInstanceUID\"].astype(str),\n    test_series[\"Anatomical_Plane\"],\n))\n\n# walk_selected() returns raw DICOM header metadata. The checkpoint slot\n# contract requires the derived columns produced by annotate().\nhte_raw = walk_selected(\"test_series\", test_ids)\nhte = annotate(hte_raw)\n\nrequired_derived = {\"fatsat\", \"fluid\", \"weight\", \"px\"}\nmissing_derived = required_derived.difference(hte.columns)\nif missing_derived:\n    raise RuntimeError(\n        f\"test metadata annotation failed; missing columns: {sorted(missing_derived)}\"\n    )\n\ncovered_test_ids = set(hte[\"StudyInstanceUID\"].astype(str))\nmissing_header_studies = sorted(set(test_ids) - covered_test_ids)\nif missing_header_studies:\n    raise RuntimeError(\n        \"test header pass did not cover every test study; \"\n        f\"missing {len(missing_header_studies)} \"\n        f\"(first={missing_header_studies[:3]})\"\n    )\n\nlog(\n    f\"test header+annotation pass: {len(hte)} series across \"\n    f\"{hte['StudyInstanceUID'].nunique()} studies\"\n)\n\n# Audit only. The model continues to use the same DICOM-header inference used\n# throughout the successful training/fine-tuning pipeline.\naudit_official_sequence_metadata(hte, test_series)\n\nprint(\n    \"Derived metadata columns ready:\",\n    {c: str(hte[c].dtype) for c in (\"fatsat\", \"fluid\", \"weight\", \"px\")}\n)\n\nbranch_packages = {\n    \"BASE\": {\n        \"path\": BASE_WEIGHTS,\n        \"manifest\": BASE_MANIFEST,\n    }\n}\nif NEED_FTC:\n    branch_packages[\"FTC\"] = {\n        \"path\": STAGE4,\n        \"manifest\": STAGE4_MANIFEST,\n    }\n\n# Exact preflight before touching pixels.\nfor branch, pack in branch_packages.items():\n    members = pack[\"manifest\"][\"members\"]\n    missing = [\n        m[\"file\"] for m in members\n        if not (pack[\"path\"] / str(m[\"file\"])).is_file()\n    ]\n    if missing:\n        raise FileNotFoundError(\n            f\"{branch} package incomplete; first missing checkpoint: {missing[0]}\"\n        )\n    log(f\"{branch}: {len(members)} complete checkpoint(s)\")\n\n# Union pixel groups so the DICOM cache is decoded only once per unique configuration.\npixel_groups = {}\nfor branch, pack in branch_packages.items():\n    for m in pack[\"manifest\"][\"members\"]:\n        pixel_groups.setdefault(m[\"pixel_group\"], []).append(\n            (branch, pack[\"path\"], m)\n        )\n\nprint(\"Unique test pixel groups:\", len(pixel_groups))\nfor key, items in pixel_groups.items():\n    cfg = json.loads(key)\n    counts = {}\n    for b, _, _ in items:\n        counts[b] = counts.get(b, 0) + 1\n    print(\n        f\"- {cfg['img']}px / {cfg['slices']} slices / group={cfg['group']} \"\n        f\"/ crop={cfg['crop_mm']}mm -> {counts}\"\n    )","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:53.337884Z","iopub.execute_input":"2026-08-11T21:20:53.338133Z","iopub.status.idle":"2026-08-11T21:20:53.426273Z","shell.execute_reply.started":"2026-08-11T21:20:53.338104Z","shell.execute_reply":"2026-08-11T21:20:53.42567Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 6. Final inference utilities","metadata":{}},{"cell_type":"code","source":"def _rank_matrix(x):\n    return (\n        pd.DataFrame(np.asarray(x))\n        .rank(method=\"average\", pct=True)\n        .to_numpy(np.float64)\n    )\n\n\ndef centered_window_subset(starts, n_keep):\n    starts = list(starts)\n    n_keep = max(1, min(int(n_keep), len(starts)))\n    if n_keep >= len(starts):\n        return starts\n    mid = (len(starts) - n_keep) // 2\n    return starts[mid:mid + n_keep]\n\n\n@torch.no_grad()\ndef predict_member_final(model, cache, mask, idx, dev, img_size, starts):\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        wins = []\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            wins.append(torch.sigmoid(logits))\n\n        probs = torch.stack(wins, dim=0)\n        pred[b0:b1] = _apply_frontier_pool(probs).cpu().numpy()\n\n    return pred\n\n\ndef aggregate_member_ranks(per_member, test_ids):\n    if not per_member:\n        raise RuntimeError(\"branch has no member predictions\")\n\n    pos = {s: i for i, s in enumerate(test_ids)}\n    M, N, T = len(per_member), len(test_ids), len(TARGETS)\n    ranks = np.full((M, N, T), np.nan, np.float64)\n\n    for mi, item in enumerate(per_member):\n        ids = item[\"ids\"]\n        rows = [pos[s] for s in ids if s in pos]\n        if len(rows) != len(ids):\n            raise RuntimeError(f\"{item['id']}: prediction contains unexpected StudyInstanceUID\")\n        if len(ids) != len(test_ids) or set(ids) != set(test_ids):\n            raise RuntimeError(\n                f\"{item['id']}: member did not cover all hidden test studies\"\n            )\n        ranks[mi, rows] = _rank_matrix(item[\"pred\"])\n\n    if np.isnan(ranks).any():\n        raise RuntimeError(\"non-finite or incomplete member-rank tensor\")\n\n    return ranks.mean(axis=0)\n\n\ndef validate_final_submission(frame, test_df):\n    expected = [\"StudyInstanceUID\", *TARGETS]\n    if frame.columns.tolist() != expected:\n        raise RuntimeError(\n            f\"submission schema mismatch: {frame.columns.tolist()} != {expected}\"\n        )\n    if len(frame) != len(test_df):\n        raise RuntimeError(\"submission row count mismatch\")\n    if frame[\"StudyInstanceUID\"].astype(str).tolist() != test_df[\"StudyInstanceUID\"].astype(str).tolist():\n        raise RuntimeError(\"submission StudyInstanceUID order mismatch\")\n    if frame[\"StudyInstanceUID\"].duplicated().any():\n        raise RuntimeError(\"duplicate StudyInstanceUID in submission\")\n    arr = frame[TARGETS].to_numpy(np.float64)\n    if not np.isfinite(arr).all():\n        raise RuntimeError(\"non-finite value in submission\")\n    if (arr < 0).any() or (arr > 1).any():\n        raise RuntimeError(\"submission values outside [0,1]\")\n    return frame","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:53.427106Z","iopub.execute_input":"2026-08-11T21:20:53.427338Z","iopub.status.idle":"2026-08-11T21:20:53.441048Z","shell.execute_reply.started":"2026-08-11T21:20:53.427319Z","shell.execute_reply":"2026-08-11T21:20:53.440148Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 7. Run BASE and, only if selected, FT-C hidden-test inference","metadata":{}},{"cell_type":"code","source":"if not torch.cuda.is_available():\n    raise RuntimeError(\"CUDA GPU is required for final inference\")\ndev = torch.device(\"cuda\")\nlog(f\"device: {dev}\")\n\nper_branch = {name: [] for name in branch_packages}\n\n# Used only for adaptive runtime protection.\nmodel_total = sum(len(p[\"manifest\"][\"members\"]) for p in branch_packages.values())\nmodel_done = 0\nobserved_fixed = None\nobserved_per_window = None\n\nfor gi, (pixel_key, items) 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)}: {IMG}px, \"\n        f\"{CACHE_SLICES} slices, group={GROUP}, crop={CROP_MM}mm\"\n    )\n\n    slot_map = pick_slots(hte, plane_map)\n\n    # Cheap metadata preflight before expensive DICOM pixel decoding.\n    slot_counts = np.asarray(\n        [len(slot_map.get(st, {})) for st in test_ids],\n        dtype=int,\n    )\n    if len(slot_counts) != len(test_ids):\n        raise RuntimeError(\"slot-map study count mismatch\")\n    if (slot_counts == 0).any():\n        zero_ids = [st for st, n in zip(test_ids, slot_counts) if n == 0]\n        log(\n            f\"WARNING: {len(zero_ids)} test study/studies have zero matching \"\n            f\"slots for pixel group {gi}; first={zero_ids[:3]}\"\n        )\n    log(\n        f\"g{gi} slot preflight: mean={slot_counts.mean():.2f}/{N_SLOT}, \"\n        f\"min={slot_counts.min()}, max={slot_counts.max()}\"\n    )\n\n    st_te, Cte, Mte = build_cache(\n        slot_map,\n        plane_map,\n        lat_of(hte, f\"test g{gi} \"),\n        f\"test g{gi}\",\n    )\n\n    if set(st_te) != set(test_ids):\n        missing = sorted(set(test_ids) - set(st_te))\n        raise RuntimeError(\n            f\"pixel group {gi} did not produce all test studies; \"\n            f\"missing {len(missing)} (first={missing[:3]})\"\n        )\n\n    idx = np.arange(len(st_te))\n    all_starts = window_starts(Cte.shape[2], GROUP)\n\n    # Put the 20-member BASE safety family first.\n    items = sorted(\n        items,\n        key=lambda x: (\n            0 if x[0] == \"BASE\" else 1,\n            int(x[2].get(\"fold\", 99)),\n            -(float(x[2].get(\"holdout\") or 0.0)),\n        ),\n    )\n\n    for branch, pkg_path, m in items:\n        model_done += 1\n        remaining_after = model_total - model_done\n        left = TIME_BUDGET - (time.time() - T0)\n\n        if left <= 0:\n            raise RuntimeError(\"final inference time budget exhausted\")\n\n        use_starts = list(all_starts)\n\n        if observed_fixed is not None and observed_per_window is not None:\n            remaining_including_current = remaining_after + 1\n            projected_each = observed_fixed + len(use_starts) * observed_per_window\n            projected_total = projected_each * remaining_including_current\n\n            if projected_total > left * 0.92:\n                room_each = left * 0.90 / max(remaining_including_current, 1)\n                n_win = int(\n                    (room_each - observed_fixed) / max(observed_per_window, 1e-9)\n                )\n                n_win = max(MIN_WINDOWS, min(len(use_starts), n_win))\n                use_starts = centered_window_subset(use_starts, n_win)\n                log(\n                    f\"{left/60:.0f} min left: runtime guard uses \"\n                    f\"{len(use_starts)}/{len(all_starts)} windows for {branch}:{m['id']}\"\n                )\n\n        ck_path = Path(pkg_path) / str(m[\"file\"])\n        t_load = time.time()\n        ck = torch.load(ck_path, map_location=\"cpu\", weights_only=False)\n\n        member_cfg = m.get(\"config\") or {}\n        model = build_model(\n            0,  # inference only; requires_grad state does not affect the forward pass\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        fp_seed = int(ck.get(\"fingerprint_seed\", 2026))\n        if \"fingerprint\" not in ck:\n            raise WeightsError(f\"{branch}:{m['id']} has no checkpoint fingerprint\")\n        check_fingerprint(\n            model,\n            dev,\n            IMG,\n            ck[\"fingerprint\"],\n            tag=f\"{branch}:{m['id']}: \",\n            seed=fp_seed,\n        )\n        t_ready = time.time()\n\n        pred = predict_member_final(\n            model, Cte, Mte, idx, dev, IMG, starts=use_starts\n        )\n        t_done = time.time()\n\n        per_branch[branch].append({\n            \"id\": m[\"id\"],\n            \"fold\": m.get(\"fold\"),\n            \"ids\": list(st_te),\n            \"pred\": pred,\n            \"n_windows\": len(use_starts),\n        })\n\n        observed_fixed = t_ready - t_load\n        observed_per_window = (t_done - t_ready) / max(len(use_starts), 1)\n\n        log(\n            f\"[{model_done}/{model_total}] {branch}:{m['id']} \"\n            f\"fold={m.get('fold')} windows={len(use_starts)} \"\n            f\"time={t_done - t_load:.0f}s\"\n        )\n\n        del model, ck, pred\n        gc.collect()\n        torch.cuda.empty_cache()\n\n    del Cte, Mte\n    gc.collect()\n    torch.cuda.empty_cache()\n\ndiag_rows = []\nfor branch, items in per_branch.items():\n    for x in items:\n        diag_rows.append({\n            \"branch\": branch,\n            \"member\": x[\"id\"],\n            \"fold\": x.get(\"fold\"),\n            \"n_windows\": x[\"n_windows\"],\n        })\ndiag = pd.DataFrame(diag_rows)\ndiag.to_csv(DIAG_DIR / \"final_inference_members.csv\", index=False)\ndisplay(diag)","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:20:53.442041Z","iopub.execute_input":"2026-08-11T21:20:53.442303Z","iopub.status.idle":"2026-08-11T21:22:06.747761Z","shell.execute_reply.started":"2026-08-11T21:20:53.442276Z","shell.execute_reply":"2026-08-11T21:22:06.746908Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 8. Build exactly one final `submission.csv`","metadata":{}},{"cell_type":"code","source":"base_rank = aggregate_member_ranks(per_branch[\"BASE\"], test_ids)\n\nif NEED_FTC:\n    ftc_rank = aggregate_member_ranks(per_branch[\"FTC\"], test_ids)\nelse:\n    ftc_rank = base_rank.copy()\n\nfinal_score = base_rank.copy()\n\nfor j, t in enumerate(TARGETS):\n    a = float(FINAL_ALPHAS[t])\n    final_score[:, j] = (\n        (1.0 - a) * base_rank[:, j]\n        + a * ftc_rank[:, j]\n    )\n\n# Final rank normalisation: the competition pipeline is rank-ensemble based,\n# so all target columns finish on the same [0,1] percentile scale.\nfinal_rank = _rank_matrix(final_score)\n\npred_frame = pd.DataFrame(final_rank, columns=TARGETS)\npred_frame.insert(0, \"StudyInstanceUID\", test_ids)\n\n# The cache order may be sorted while test.csv has its own official order.\nsubmission = (\n    test_df[[\"StudyInstanceUID\"]]\n    .merge(pred_frame, on=\"StudyInstanceUID\", how=\"left\")\n)\n\nif submission[TARGETS].isna().any().any():\n    raise RuntimeError(\"final inference missed one or more hidden test studies\")\n\nsubmission = validate_final_submission(submission, test_df)\nsubmission.to_csv(FINAL_PATH, index=False)\n\n# Validate the exact bytes/table that will be submitted, not only the in-memory frame.\nsubmission_disk = pd.read_csv(\n    FINAL_PATH, dtype={\"StudyInstanceUID\": str}\n)\nsubmission_disk = validate_final_submission(\n    submission_disk,\n    test_df.astype({\"StudyInstanceUID\": str}),\n)\nif FINAL_PATH.stat().st_size <= 0:\n    raise RuntimeError(\"submission.csv was created but is empty\")\n\n# A small audit file, but NO second submission candidate.\nfinal_status = {\n    \"final_ok\": True,\n    \"submission_path\": str(FINAL_PATH),\n    \"rows\": int(len(submission)),\n    \"targets\": TARGETS,\n    \"base_members_used\": int(len(per_branch[\"BASE\"])),\n    \"ftc_members_used\": int(len(per_branch.get(\"FTC\", []))),\n    \"ftc_inference_required\": bool(NEED_FTC),\n    \"target_ftc_alphas\": {k: float(v) for k, v in FINAL_ALPHAS.items()},\n    \"selection_rule\": \"nested expert-CV conservative rank blend; BASE fallback\",\n}\n(DIAG_DIR / \"final_status.json\").write_text(json.dumps(final_status, indent=2))\n\nprint(\"=\" * 72)\nprint(\"FINAL SUBMISSION READY\")\nprint(\"Submit this file and only this file:\")\nprint(FINAL_PATH)\nprint(\"=\" * 72)\nprint(json.dumps(final_status, indent=2))\ndisplay(submission.head())","metadata":{"execution":{"iopub.status.busy":"2026-08-11T21:22:06.748879Z","iopub.execute_input":"2026-08-11T21:22:06.749511Z","iopub.status.idle":"2026-08-11T21:22:06.785739Z","shell.execute_reply.started":"2026-08-11T21:22:06.749475Z","shell.execute_reply":"2026-08-11T21:22:06.785196Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Final output\n\nAfter a successful `Save Version / Run All`, submit:\n\n**`submission.csv`**\n\nDo not submit files inside `final_diagnostics/`; they are audit metadata only.","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}