MCPcopy Create free account
hub / github.com/OpenGVLab/UniFormerV2 / build_model

Function build_model

extract_clip/model.py:399–436  ·  view source on GitHub ↗
(state_dict: dict)

Source from the content-addressed store, hash-verified

397
398
399def build_model(state_dict: dict):
400 vit = "visual.proj" in state_dict
401
402 if vit:
403 vision_width = state_dict["visual.conv1.weight"].shape[0]
404 vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405 vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406 grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407 image_resolution = vision_patch_size * grid_size
408 else:
409 counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
410 vision_layers = tuple(counts)
411 vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412 output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413 vision_patch_size = None
414 assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415 image_resolution = output_width * 32
416
417 embed_dim = state_dict["text_projection"].shape[1]
418 context_length = state_dict["positional_embedding"].shape[0]
419 vocab_size = state_dict["token_embedding.weight"].shape[0]
420 transformer_width = state_dict["ln_final.weight"].shape[0]
421 transformer_heads = transformer_width // 64
422 transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
424 model = CLIP(
425 embed_dim,
426 image_resolution, vision_layers, vision_width, vision_patch_size,
427 context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428 )
429
430 for key in ["input_resolution", "context_length", "vocab_size"]:
431 if key in state_dict:
432 del state_dict[key]
433
434 convert_weights(model)
435 model.load_state_dict(state_dict)
436 return model.eval()

Callers 1

loadFunction · 0.90

Calls 2

CLIPClass · 0.85
convert_weightsFunction · 0.85

Tested by

no test coverage detected