MCPcopy Create free account
hub / github.com/Monalissaa/DisenDiff / build_model

Function build_model

clip/model.py:405–442  ·  view source on GitHub ↗
(state_dict: dict)

Source from the content-addressed store, hash-verified

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

Callers 1

loadFunction · 0.85

Calls 2

CLIPClass · 0.85
convert_weightsFunction · 0.85

Tested by

no test coverage detected