{"version":2,"relationshipURLBase":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html","relationshipResolution":"Resolve relative relationship URLs against relationshipURLBase; complete records and absolute URLs are in blocks.","title":"冻结参数以后才使用标签 · 实现代码","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html","markdown":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.md","pages":[{"id":"reading-opening","title":"冻结参数以后才使用标签 · 实现代码","unit":"冻结参数以后才使用标签 · 实现代码","unitId":"notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f","chapter":"course","number":1}],"aliases":[{"oldId":"b-e95c425e72d9cbe442effa9e","targetId":"b-e95c425e72d9cbe442effa9e","page":"reading-opening","operation":"move","beforeSHA256":"88a04c9ecb442ccaa48afb715979a4f7ec256d11b69e583a238c98ab9d60e977","afterSHA256":"88a04c9ecb442ccaa48afb715979a4f7ec256d11b69e583a238c98ab9d60e977","reason":"Same source body in authored semantic page"},{"oldId":"b-527b4eaee0a10fa356641a74","targetId":"b-527b4eaee0a10fa356641a74","page":"reading-opening","operation":"move","beforeSHA256":"68319e5e5a34c55c5c37eacf5d8d3771d3e9bb07fac421ee8df5a6123548a17a","afterSHA256":"68319e5e5a34c55c5c37eacf5d8d3771d3e9bb07fac421ee8df5a6123548a17a","reason":"Same source body in authored semantic page"},{"oldId":"b-bcbbe90a5f696905db57669e","targetId":"b-bcbbe90a5f696905db57669e","page":"reading-opening","operation":"move","beforeSHA256":"e91f24e4e4ca40e2099a0d81d30db6568f4bf2074b499eeee6e3959617bd97ac","afterSHA256":"e91f24e4e4ca40e2099a0d81d30db6568f4bf2074b499eeee6e3959617bd97ac","reason":"Same source body in authored semantic page"},{"oldId":"b-f7f7178d8b965f14ff25038b","targetId":"b-f7f7178d8b965f14ff25038b","page":"reading-opening","operation":"move","beforeSHA256":"2a269d38480454fbc554b17f926927738416555e36045ec5fe468ba056454f5d","afterSHA256":"2a269d38480454fbc554b17f926927738416555e36045ec5fe468ba056454f5d","reason":"Same source body in authored semantic page"},{"oldId":"b-a318164a303d5a9847871e16","targetId":"b-a318164a303d5a9847871e16","page":"reading-opening","operation":"move","beforeSHA256":"e9fde753df3fb203edecd3b68df41ad9a34a08ef27da8b8736f3ba884a834315","afterSHA256":"e9fde753df3fb203edecd3b68df41ad9a34a08ef27da8b8736f3ba884a834315","reason":"Same source body in authored semantic page"}],"blocks":[{"id":"b-e95c425e72d9cbe442effa9e","type":"p","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html#b-e95c425e72d9cbe442effa9e","content":"[LAB 07 · MoCo：历史 key、队列与两种更新](/course/notebooks/0d1b8f6fbf6a476c93ffcc169f2ec1f4.html)","sha256":"88a04c9ecb442ccaa48afb715979a4f7ec256d11b69e583a238c98ab9d60e977","chapter":{"id":"course","title":"冻结参数以后才使用标签 · 实现代码"},"unit":{"id":"notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f","title":"冻结参数以后才使用标签 · 实现代码"},"page":{"id":"reading-opening","title":"冻结参数以后才使用标签 · 实现代码","number":1},"sectionTitle":"冻结参数以后才使用标签 · 实现代码","currentQuestion":"冻结参数以后才使用标签 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":null,"nextBlock":"b-527b4eaee0a10fa356641a74","prerequisites":[],"relatedBlocks":[]},{"id":"b-527b4eaee0a10fa356641a74","type":"h1","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html#b-527b4eaee0a10fa356641a74","content":"# 冻结参数以后才使用标签 · 实现代码","sha256":"68319e5e5a34c55c5c37eacf5d8d3771d3e9bb07fac421ee8df5a6123548a17a","chapter":{"id":"course","title":"冻结参数以后才使用标签 · 实现代码"},"unit":{"id":"notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f","title":"冻结参数以后才使用标签 · 实现代码"},"page":{"id":"reading-opening","title":"冻结参数以后才使用标签 · 实现代码","number":1},"sectionTitle":"冻结参数以后才使用标签 · 实现代码","currentQuestion":"冻结参数以后才使用标签 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-e95c425e72d9cbe442effa9e","nextBlock":"b-bcbbe90a5f696905db57669e","prerequisites":[{"id":"b-e95c425e72d9cbe442effa9e","url":"#b-e95c425e72d9cbe442effa9e","role":"problem-context"}],"relatedBlocks":[]},{"id":"b-bcbbe90a5f696905db57669e","type":"p","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html#b-bcbbe90a5f696905db57669e","content":"按问题继续","sha256":"e91f24e4e4ca40e2099a0d81d30db6568f4bf2074b499eeee6e3959617bd97ac","chapter":{"id":"course","title":"冻结参数以后才使用标签 · 实现代码"},"unit":{"id":"notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f","title":"冻结参数以后才使用标签 · 实现代码"},"page":{"id":"reading-opening","title":"冻结参数以后才使用标签 · 实现代码","number":1},"sectionTitle":"冻结参数以后才使用标签 · 实现代码","currentQuestion":"冻结参数以后才使用标签 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-527b4eaee0a10fa356641a74","nextBlock":"b-f7f7178d8b965f14ff25038b","prerequisites":[{"id":"b-527b4eaee0a10fa356641a74","url":"#b-527b4eaee0a10fa356641a74","role":"section-title"},{"id":"b-e95c425e72d9cbe442effa9e","url":"#b-e95c425e72d9cbe442effa9e","role":"problem-context"}],"relatedBlocks":[]},{"id":"b-f7f7178d8b965f14ff25038b","type":"p","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html#b-f7f7178d8b965f14ff25038b","content":"真实FIFO键、EMA、梯度更新及低于随机基线的保留结果","sha256":"2a269d38480454fbc554b17f926927738416555e36045ec5fe468ba056454f5d","chapter":{"id":"course","title":"冻结参数以后才使用标签 · 实现代码"},"unit":{"id":"notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f","title":"冻结参数以后才使用标签 · 实现代码"},"page":{"id":"reading-opening","title":"冻结参数以后才使用标签 · 实现代码","number":1},"sectionTitle":"冻结参数以后才使用标签 · 实现代码","currentQuestion":"冻结参数以后才使用标签 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-bcbbe90a5f696905db57669e","nextBlock":"b-a318164a303d5a9847871e16","prerequisites":[{"id":"b-527b4eaee0a10fa356641a74","url":"#b-527b4eaee0a10fa356641a74","role":"section-title"},{"id":"b-e95c425e72d9cbe442effa9e","url":"#b-e95c425e72d9cbe442effa9e","role":"problem-context"}],"relatedBlocks":[]},{"id":"b-a318164a303d5a9847871e16","type":"pre","scope":"document","url":"https://codingai-lec03.pages.dev/course/notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f.html#b-a318164a303d5a9847871e16","content":"```\ndef evaluate(model,x,ys,yc,train,test):\n    model.eval()\n    with torch.no_grad(): h,z=model(x)\n    scores={}\n    for space,features in [('h',h),('z',z)]:\n        a=F.normalize(features,dim=1).numpy()\n        for target,y in [('shape',ys),('color',yc)]:\n            knn=KNeighborsClassifier(n_neighbors=5,metric='cosine')\n            knn.fit(a[train],y[train])\n            # Standardization and classifier fit use TRAIN only; test used once for reporting.\n            linear=make_pipeline(StandardScaler(),LogisticRegression(C=1,max_iter=1000))\n            linear.fit(a[train],y[train])\n            scores[f'{space}_{target}_knn']=float(knn.score(a[test],y[test]))\n            scores[f'{space}_{target}_linear']=float(linear.score(a[test],y[test]))\n    with torch.no_grad():\n        # Counterfactual hue swap only: same geometry and pixels, channels exchanged.\n        ah,az=model(x[test][:,[2,1,0]])\n        for space,original,other in [('h',h[test],ah),('z',z[test],az)]:\n            scores[f'{space}_hue_swap_cosine']=float(F.cosine_similarity(original,other).mean())\n    return scores\n\ndef plot_results(out,x,initial,models,results,histories):\n    fig,ax=plt.subplots(3,6,figsize=(12,6))\n    ids=[0,100,140,280,420,700]\n    torch.manual_seed(SEED+6)\n    for j,i in enumerate(ids):\n        ax[0,j].imshow(x[i].permute(1,2,0));ax[0,j].set_title(f'source {i}')\n        paired_state=torch.get_rng_state()\n        for row,erase in [(1,False),(2,True)]:\n            torch.set_rng_state(paired_state)\n            ax[row,j].imshow(views(x[i:i+1],erase)[0].permute(1,2,0))\n    for row,label in enumerate(['source','view: hue kept','view: hue can swap']):ax[row,0].set_ylabel(label)\n    for a in ax.flat:a.set_xticks([]);a.set_yticks([])\n    fig.tight_layout();fig.savefig(out/'views.png',dpi=140);plt.close(fig)\n    fig,axes=plt.subplots(1,3,figsize=(14,4))\n    for name,hist in histories.items():axes[0].plot(np.arange(1,len(hist)+1),hist,label=name)\n    axes[0].set(xlabel='epoch',ylabel='InfoNCE (batch mean)',title='Training objective');axes[0].legend(fontsize=8)\n    names=list(results)\n    for ax,task in zip(axes[1:],['shape','color']):\n        pos=np.arange(len(names)); width=.34\n        for off,space in [(-width/2,'h'),(width/2,'z')]:\n            ax.bar(pos+off,[results[n][f'{space}_{task}_knn'] for n in names],width,label=space)\n        ax.set_xticks(pos,names,rotation=20);ax.set_ylim(0,1.05);ax.set_title(f'Frozen cosine 5-NN: {task}')\n        ax.set_ylabel('held-out accuracy');ax.legend()\n    fig.tight_layout();fig.savefig(out/'training-and-probes.png',dpi=140);plt.close(fig)\n\ndef run_contrastive(out_dir='lab06-output',mode='color'):\n    started=time.time();out=Path(out_dir);out.mkdir(parents=True,exist_ok=True)\n    torch.manual_seed(SEED)\n    x,ys,yc,train,test=make_data()\n    np.savez_compressed(out/'inputs.npz',images=x.numpy(),shape=ys,color=yc,train_ids=train,test_ids=test)\n    initial=ContrastiveModel(); torch.save(initial.state_dict(),out/'random-init.pt')\n    results={'random':evaluate(initial,x,ys,yc,train,test)};histories={};models={};deltas={}\n    if mode=='color':\n        for name,erase in [('keep-hue',False),('swap-hue',True)]:\n            model,hist,delta=train_simclr(initial,x,train,erase)\n            results[name]=evaluate(model,x,ys,yc,train,test);histories[name]=hist;models[name]=model;deltas[name]=delta\n            torch.save(model.state_dict(),out/f'{name}.pt')\n    else:\n        model,hist,delta=train_simclr(initial,x,train,False)\n        results['simclr']=evaluate(model,x,ys,yc,train,test);histories['simclr']=hist;models['simclr']=model;deltas['simclr']=delta\n        torch.save(model.state_dict(),out/'simclr.pt')\n        query,key,queue,queue_ids,hist,trace,delta=train_moco(initial,x,train)\n        results['moco-toy']=evaluate(query,x,ys,yc,train,test);histories['moco-toy']=hist;models['moco-toy']=query;deltas['moco-toy']=delta\n        torch.save({'query':query.state_dict(),'key':key.state_dict(),'queue':queue,'queue_ids':queue_ids},out/'moco-toy.pt')\n        (out/'queue-trace.json').write_text(json.dumps(trace,indent=2))\n    config={'seed':SEED,'mode':mode,'image_shape':[3,16,16],'train_n':len(train),'test_n':len(test),'batch_size':60,'epochs_simclr':40,'epochs_moco':15,'tau':.2,'adam_lr':.002,'h_dim':48,'z_dim':24,'labels_used_only_for_probes':True,'knn':{'k':5,'metric':'cosine'},'linear_probe':{'regularization_C':1,'standardizer_fit':'train-only'},'test_tuning':'none; fixed protocol before first run'}\n    (out/'config.json').write_text(json.dumps(config,indent=2))\n    plot_results(out,x,initial,models,results,histories)\n    payload={'code_sha256':globals().get('SOURCE_SHA256') or hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'kind':'local CPU full training + frozen held-out probes','utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'seconds':time.time()-started,'torch':torch.__version__,'numpy':np.__version__,'python':platform.python_version(),'scores':results,'loss_history':histories,'encoder_weight_l2_change':deltas,'warmup':moco_warmup(),'inputs_sha256':hashlib.sha256((out/'inputs.npz').read_bytes()).hexdigest()}\n    (out/'results.json').write_text(json.dumps(payload,indent=2))\n    print(json.dumps({'scores':results,'encoder_weight_l2_change':deltas,'seconds':payload['seconds']},indent=2))\n    return payload\n```","sha256":"e9fde753df3fb203edecd3b68df41ad9a34a08ef27da8b8736f3ba884a834315","chapter":{"id":"course","title":"冻结参数以后才使用标签 · 实现代码"},"unit":{"id":"notebook-blocks/a9e41aad60464c2eb480c6268c6ed67f","title":"冻结参数以后才使用标签 · 实现代码"},"page":{"id":"reading-opening","title":"冻结参数以后才使用标签 · 实现代码","number":1},"sectionTitle":"冻结参数以后才使用标签 · 实现代码","currentQuestion":"冻结参数以后才使用标签 · 实现代码","sourceSlides":[],"knowledgeBlock":null,"formulas":[],"previousBlock":"b-f7f7178d8b965f14ff25038b","nextBlock":null,"prerequisites":[{"id":"b-527b4eaee0a10fa356641a74","url":"#b-527b4eaee0a10fa356641a74","role":"section-title"},{"id":"b-e95c425e72d9cbe442effa9e","url":"#b-e95c425e72d9cbe442effa9e","role":"problem-context"}],"relatedBlocks":[]}]}
