Add four verified v2.5 LiteRT cascade models, Cadryl contracts and bilingual 680-image benchmark
17133be verified Download conversion/cascade-v25/inference.py from fireviewer/litert-models: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/fireviewer/litert-models/resolve/main/conversion/cascade-v25/inference.py
- Command line
-
hf download hf://fireviewer/litert-models/conversion/cascade-v25/inference.py
-
curl -L -o inference.py https://huggingface.co/fireviewer/litert-models/resolve/main/conversion/cascade-v25/inference.py
11.3 kB
| """Explicit, tensor-only loading for FireViewer v2.5 research checkpoints. | |
| No automatic Hugging Face trust_remote_code, cloud credentials or smoke point model. | |
| The optional smoke backbone uses a pinned official facebookresearch source. | |
| """ | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| import argparse, hashlib, json, math, tempfile | |
| import numpy as np | |
| from PIL import Image | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from safetensors.torch import load_file | |
| class FlameHeatmap(nn.Module): | |
| def __init__(self,backbone): | |
| super().__init__(); self.backbone=backbone | |
| self.head=nn.Sequential(nn.Conv2d(backbone.config.hidden_size,128,3,padding=1),nn.GroupNorm(8,128),nn.GELU(), | |
| nn.Upsample(scale_factor=2,mode='bilinear',align_corners=False),nn.Conv2d(128,64,3,padding=1), | |
| nn.GroupNorm(8,64),nn.GELU(),nn.Upsample(scale_factor=2,mode='bilinear',align_corners=False),nn.Conv2d(64,1,1)) | |
| def forward(self,x): | |
| tokens=self.backbone(pixel_values=x).last_hidden_state[:,1:] | |
| side=x.shape[-1]//self.backbone.config.patch_size | |
| return self.head(tokens.transpose(1,2).reshape(x.shape[0],-1,side,side)).squeeze(1) | |
| class SmokeClassifier(nn.Module): | |
| def __init__(self,backbone): | |
| super().__init__(); self.backbone=backbone | |
| self.head=nn.Sequential(nn.LayerNorm(384),nn.Dropout(.15),nn.Linear(384,1)) | |
| def forward(self,x):return self.head(self.backbone(x)).squeeze(1) | |
| def sha(path): | |
| h=hashlib.sha256() | |
| with open(path,'rb') as f: | |
| for b in iter(lambda:f.read(8<<20),b''):h.update(b) | |
| return h.hexdigest() | |
| def load_model(directory,device='cpu'): | |
| """Load a downloaded, revision-pinned model repository directory.""" | |
| root=Path(directory); config=json.loads((root/'config.json').read_text()) | |
| proof=json.loads((root/'provenance/checkpoint-export.json').read_text()) | |
| assert sha(root/'model.safetensors')==proof['safe_weights_sha256'], 'weights checksum mismatch' | |
| state=load_file(root/'model.safetensors',device='cpu') | |
| kind=config['model_kind'] | |
| if kind=='rfdetr': | |
| import importlib.metadata | |
| from rfdetr import RFDETRMedium | |
| if importlib.metadata.version('rfdetr')!='1.11.0': | |
| raise RuntimeError('Install rfdetr==1.11.0 for this checkpoint') | |
| # RF-DETR 1.11 expects a native wrapper. Construct it from local safe tensors | |
| # and plain JSON; no externally supplied pickle is loaded by this helper. | |
| with tempfile.TemporaryDirectory(prefix='fireviewer-rfdetr-') as tmp: | |
| native=Path(tmp)/'local_safe_wrapper.pth' | |
| torch.save(dict(model=state,args=SimpleNamespace(**config['checkpoint_args']), | |
| epoch=config['selected_epoch']-1),native) | |
| model=RFDETRMedium(pretrain_weights=str(native),resolution=config['resolution'], | |
| positional_encoding_size=config['positional_encoding_size'],num_classes=1, | |
| num_select=300,device=device,compile=False,gradient_checkpointing=False) | |
| return model,config | |
| if kind=='flame_point': | |
| from transformers import Dinov2Config,Dinov2Model | |
| model=FlameHeatmap(Dinov2Model(Dinov2Config(**config['backbone_config']))) | |
| # Transformers 5 renamed the separate attention projections. Values, | |
| # shapes and the model architecture remain unchanged; loading stays strict. | |
| if 'backbone.encoder.layer.0.attention.q_proj.weight' in model.state_dict(): | |
| aliases={'.attention.attention.query.':'.attention.q_proj.', | |
| '.attention.attention.key.':'.attention.k_proj.', | |
| '.attention.attention.value.':'.attention.v_proj.', | |
| '.attention.output.dense.':'.attention.o_proj.'} | |
| renamed={} | |
| for key,value in state.items(): | |
| target=key | |
| for old,new in aliases.items():target=target.replace(old,new) | |
| if target in renamed:raise RuntimeError('Attention alias collision') | |
| renamed[target]=value | |
| state=renamed | |
| elif kind=='smoke_classifier': | |
| revision=config['dino_source_revision'] | |
| if revision!='7764ea0f912e53c92e82eb78a2a1631e92725fc8': | |
| raise ValueError('Unexpected official DINOv2 source revision') | |
| backbone=torch.hub.load('facebookresearch/dinov2:'+revision,'dinov2_vits14', | |
| pretrained=False,trust_repo=True,skip_validation=False) | |
| model=SmokeClassifier(backbone) | |
| else:raise ValueError(kind) | |
| model.load_state_dict(state,strict=True) | |
| model.to(device).eval();return model,config | |
| def preprocess(crop,config,device): | |
| interpolation=Image.Resampling.BICUBIC if config['model_kind']=='smoke_classifier' else Image.Resampling.BILINEAR | |
| rgb=np.array(crop.convert('RGB').resize((config['resolution'],config['resolution']),interpolation),copy=True) | |
| x=torch.from_numpy(rgb).permute(2,0,1).float()/255 | |
| mean=torch.tensor(config['normalization']['mean'])[:,None,None] | |
| std=torch.tensor(config['normalization']['std'])[:,None,None] | |
| return ((x-mean)/std)[None].to(device) | |
| def heatmap_point(logits): | |
| a=logits.float();n,h,w=a.shape;peak=a.flatten(1).argmax(1);px=peak%w;py=peak//w | |
| yy,xx=torch.meshgrid(torch.arange(h,device=a.device),torch.arange(w,device=a.device),indexing='ij') | |
| local=(xx[None]-px[:,None,None]).abs().le(2)&(yy[None]-py[:,None,None]).abs().le(2) | |
| p=F.softmax(a.masked_fill(~local,-1e4).flatten(1),dim=1).reshape_as(a) | |
| return torch.stack([(p*(xx+.5)/w).sum((1,2)),(p*(yy+.5)/h).sum((1,2))],1) | |
| def predict_point(model,config,crop,device='cpu'): | |
| logits=model(preprocess(crop,config,device)) | |
| assert torch.isfinite(logits).all() | |
| uv=heatmap_point(logits)[0].cpu().tolist() | |
| return dict(semantic='flame_base_anchor',point_normalized=uv, | |
| point_xy=[uv[0]*crop.width,uv[1]*crop.height],confidence=None) | |
| def predict_smoke(model,config,crop,device='cpu'): | |
| logit=model(preprocess(crop,config,device)).float()[0] | |
| assert torch.isfinite(logit) | |
| probability=float(torch.sigmoid(logit/config['temperature']).cpu()) | |
| low=config['low_threshold'];high=config['high_threshold'] | |
| status=('low_compatibility' if low is not None and probability<=low else | |
| 'fire_smoke_probable' if high is not None and probability>=high else 'ambiguous') | |
| return dict(semantic='fire_associated_smoke_compatible',probability=probability,status=status, | |
| source_location=None) | |
| def area(b):return max(0,b[2]-b[0])*max(0,b[3]-b[1]) | |
| def iou(a,b): | |
| intersection=area([max(a[0],b[0]),max(a[1],b[1]),min(a[2],b[2]),min(a[3],b[3])]) | |
| return intersection/max(1e-12,area(a)+area(b)-intersection) | |
| def nms(boxes,scores,threshold,limit=None): | |
| keep=[] | |
| for i in sorted(range(len(scores)),key=lambda i:(-float(scores[i]),i)): | |
| if area(boxes[i])>0 and all(iou(boxes[i],boxes[j])<=threshold for j in keep):keep.append(i) | |
| if limit is not None and len(keep)>=limit:break | |
| return keep | |
| def expand_roi(box,size,context=.30,min_side=128): | |
| width,height=size;x0,y0,x1,y1=map(float,box);cx,cy=(x0+x1)/2,(y0+y1)/2 | |
| w=max(min_side,(x1-x0)*(1+2*context));h=max(min_side,(y1-y0)*(1+2*context)) | |
| return [max(0,math.floor(cx-w/2)),max(0,math.floor(cy-h/2)),min(width,math.ceil(cx+w/2)),min(height,math.ceil(cy+h/2))] | |
| def tight_roi(box,size): | |
| width,height=size | |
| return [max(0,math.floor(box[0])),max(0,math.floor(box[1])),min(width,math.ceil(box[2])),min(height,math.ceil(box[3]))] | |
| def detections(model,image,threshold): | |
| result=model.predict(image,threshold=threshold,include_source_image=False) | |
| mask=result.class_id==0 | |
| return result.xyxy[mask].tolist(),result.confidence[mask].tolist() | |
| def cascade(image,proposal,visible,point_model=None,smoke_model=None,device='cpu',flame_threshold=.25): | |
| """Research comparison recipe; detector thresholds are not calibrated alert thresholds.""" | |
| proposals,proposal_scores=detections(proposal[0],image,.10) | |
| selected=nms(proposals,proposal_scores,.75,6) | |
| boxes=[];scores=[];roi_records=[] | |
| for idx in selected: | |
| box=proposals[idx];roi=expand_roi(box,image.size,.30,128) | |
| found,conf=detections(visible[0],image.crop(roi),flame_threshold) | |
| local_keep=list(range(len(found))) | |
| for j in local_keep: | |
| b=found[j] | |
| mapped=[max(roi[0],b[0]+roi[0]),max(roi[1],b[1]+roi[1]), | |
| min(roi[2],b[2]+roi[0]),min(roi[3],b[3]+roi[1])] | |
| if area(mapped)>0:boxes.append(mapped);scores.append(conf[j]) | |
| roi_records.append(dict(proposal_bbox_xyxy=box,proposal_score=proposal_scores[idx], | |
| visible_flame_found=bool(local_keep))) | |
| flames=[] | |
| for idx in nms(boxes,scores,.60,100): | |
| entry=dict(bbox_xyxy=boxes[idx],score=scores[idx],semantic='visible_flame') | |
| if point_model: | |
| roi=tight_roi(boxes[idx],image.size) | |
| if roi[2]>roi[0] and roi[3]>roi[1]: | |
| prediction=predict_point(*point_model,image.crop(roi),device=device) | |
| prediction['point_xy_original']=[prediction['point_xy'][0]+roi[0],prediction['point_xy'][1]+roi[1]] | |
| entry['point']=prediction | |
| flames.append(entry) | |
| smoke=[] | |
| if smoke_model: | |
| for r in roi_records: | |
| if r['visible_flame_found']:continue | |
| roi=expand_roi(r['proposal_bbox_xyxy'],image.size,.45,160) | |
| smoke.append(dict(roi_xyxy=roi,proposal_bbox_xyxy=r['proposal_bbox_xyxy'], | |
| **predict_smoke(*smoke_model,image.crop(roi),device=device))) | |
| return dict(image_size=list(image.size),visible_flames=flames,smoke_compatibility=smoke, | |
| detector_thresholds_calibrated=False,point_semantic='flame_base_anchor', | |
| fire_group_association_performed=False) | |
| def main(): | |
| p=argparse.ArgumentParser(description=__doc__) | |
| p.add_argument('--model-dir');p.add_argument('--proposal-dir');p.add_argument('--visible-dir');p.add_argument('--point-dir');p.add_argument('--smoke-dir') | |
| p.add_argument('--image',required=True);p.add_argument('--device',default='cpu');p.add_argument('--output',required=True) | |
| args=p.parse_args();image=Image.open(args.image).convert('RGB') | |
| if args.model_dir: | |
| model,config=load_model(args.model_dir,args.device) | |
| if config['model_kind']=='flame_point':result=predict_point(model,config,image,args.device) | |
| elif config['model_kind']=='smoke_classifier':result=predict_smoke(model,config,image,args.device) | |
| else: | |
| boxes,scores=detections(model,image,.25);result=dict(bbox_xyxy=boxes,scores=scores,semantic=config['semantic']) | |
| else: | |
| if not(args.proposal_dir and args.visible_dir):p.error('Supply --model-dir, or both detector directories') | |
| proposal=load_model(args.proposal_dir,args.device);visible=load_model(args.visible_dir,args.device) | |
| point=load_model(args.point_dir,args.device) if args.point_dir else None | |
| smoke=load_model(args.smoke_dir,args.device) if args.smoke_dir else None | |
| result=cascade(image,proposal,visible,point,smoke,args.device) | |
| Path(args.output).write_text(json.dumps(result,indent=2)) | |
| if __name__=='__main__':main() | |