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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
COCO_PANOPTIC_CLASSES = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', 'door-stuff', 'floor-wood', 'flower', 'fruit', 'gravel', 'house', 'light', 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', 'wall-wood', 'water-other', 'window-blind', 'window-other', 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', 'cabinet-merged', 'table-merged', 'floor-other-merged', 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', 'paper-merged', 'food-other-merged', 'building-other-merged', 'rock-merged', 'wall-other-merged', 'rug-merged']
|
| 2 |
+
|
| 3 |
+
COCO_SEMANTIC_CLASSES = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'street sign', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'hat', 'backpack', 'umbrella', 'shoe', 'eye glasses', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'plate', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'mirror', 'dining table', 'window', 'desk', 'toilet', 'door', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'blender', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'hair brush']
|
| 4 |
+
|
| 5 |
+
ADE_PANOPTIC_CLASSES = ['wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed', 'window', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchair', 'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp', 'tub', 'rail', 'cushion', 'base', 'box', 'column', 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', 'path', 'stairs', 'runway', 'case', 'pool table', 'pillow', 'screen door', 'stairway', 'river', 'bridge', 'bookcase', 'blind', 'coffee table', 'toilet', 'flower', 'book', 'hill', 'bench', 'countertop', 'stove', 'palm', 'kitchen island', 'computer', 'swivel chair', 'boat', 'bar', 'arcade machine', 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', 'chandelier', 'awning', 'street lamp', 'booth', 'tv', 'airplane', 'dirt track', 'clothes', 'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle', 'buffet', 'poster', 'stage', 'van', 'ship', 'fountain', 'conveyer belt', 'canopy', 'washer', 'plaything', 'pool', 'stool', 'barrel', 'basket', 'falls', 'tent', 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', 'step', 'tank', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', 'lake', 'dishwasher', 'screen', 'blanket', 'sculpture', 'hood', 'sconce', 'vase', 'traffic light', 'tray', 'trash can', 'fan', 'pier', 'crt screen', 'plate', 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', 'clock', 'flag']
|
| 6 |
+
|
| 7 |
+
ADE20K_847 = ['wall', 'building', 'sky', 'tree', 'road', 'floor', 'ceiling', 'bed', 'sidewalk', 'earth', 'cabinet', 'person', 'grass', 'windowpane', 'car', 'mountain', 'plant', 'table', 'chair', 'curtain', 'door', 'sofa', 'sea', 'painting', 'water', 'mirror', 'house', 'rug', 'shelf', 'armchair', 'fence', 'field', 'lamp', 'rock', 'seat', 'river', 'desk', 'bathtub', 'railing', 'signboard', 'cushion', 'path', 'work surface', 'stairs', 'column', 'sink', 'wardrobe', 'snow', 'refrigerator', 'base', 'bridge', 'blind', 'runway', 'cliff', 'sand', 'fireplace', 'pillow', 'screen door', 'toilet', 'skyscraper', 'grandstand', 'box', 'pool table', 'palm', 'double door', 'coffee table', 'counter', 'countertop', 'chest of drawers', 'kitchen island', 'boat', 'waterfall', 'stove', 'flower', 'bookcase', 'controls', 'book', 'stairway', 'streetlight', 'computer', 'bus', 'swivel chair', 'light', 'bench', 'case', 'towel', 'fountain', 'embankment', 'television receiver', 'van', 'hill', 'awning', 'poster', 'truck', 'airplane', 'pole', 'tower', 'court', 'ball', 'aircraft carrier', 'buffet', 'hovel', 'apparel', 'minibike', 'animal', 'chandelier', 'step', 'booth', 'bicycle', 'doorframe', 'sconce', 'pond', 'trade name', 'bannister', 'bag', 'traffic light', 'gazebo', 'escalator', 'land', 'board', 'arcade machine', 'eiderdown', 'bar', 'stall', 'playground', 'ship', 'ottoman', 'ashcan', 'bottle', 'cradle', 'pot', 'conveyer belt', 'train', 'stool', 'lake', 'tank', 'ice', 'basket', 'manhole', 'tent', 'canopy', 'microwave', 'barrel', 'dirt track', 'beam', 'dishwasher', 'plate', 'screen', 'ruins', 'washer', 'blanket', 'plaything', 'food', 'screen', 'oven', 'stage', 'beacon', 'umbrella', 'sculpture', 'aqueduct', 'container', 'scaffolding', 'hood', 'curb', 'roller coaster', 'horse', 'catwalk', 'glass', 'vase', 'central reservation', 'carousel', 'radiator', 'closet', 'machine', 'pier', 'fan', 'inflatable bounce game', 'pitch', 'paper', 'arcade', 'hot tub', 'helicopter', 'tray', 'partition', 'vineyard', 'bowl', 'bullring', 'flag', 'pot', 'footbridge', 'shower', 'bag', 'bulletin board', 'confessional booth', 'trunk', 'forest', 'elevator door', 'laptop', 'instrument panel', 'bucket', 'tapestry', 'platform', 'jacket', 'gate', 'monitor', 'telephone booth', 'spotlight', 'ring', 'control panel', 'blackboard', 'air conditioner', 'chest', 'clock', 'sand dune', 'pipe', 'vault', 'table football', 'cannon', 'swimming pool', 'fluorescent', 'statue', 'loudspeaker', 'exhibitor', 'ladder', 'carport', 'dam', 'pulpit', 'skylight', 'water tower', 'grill', 'display board', 'pane', 'rubbish', 'ice rink', 'fruit', 'patio', 'vending machine', 'telephone', 'net', 'backpack', 'jar', 'track', 'magazine', 'shutter', 'roof', 'banner', 'landfill', 'post', 'altarpiece', 'hat', 'arch', 'table game', 'bag', 'document', 'dome', 'pier', 'shanties', 'forecourt', 'crane', 'dog', 'piano', 'drawing', 'cabin', 'ad', 'amphitheater', 'monument', 'henhouse', 'cockpit', 'heater', 'windmill', 'pool', 'elevator', 'decoration', 'labyrinth', 'text', 'printer', 'mezzanine', 'mattress', 'straw', 'stalls', 'patio', 'billboard', 'bus stop', 'trouser', 'console table', 'rack', 'notebook', 'shrine', 'pantry', 'cart', 'steam shovel', 'porch', 'postbox', 'figurine', 'recycling bin', 'folding screen', 'telescope', 'deck chair', 'kennel', 'coffee maker', 'altar', 'fish', 'easel', 'artificial golf green', 'iceberg', 'candlestick', 'shower stall', 'television stand', 'wall socket', 'skeleton', 'grand piano', 'candy', 'grille door', 'pedestal', 'jersey', 'shoe', 'gravestone', 'shanty', 'structure', 'rocking chair', 'bird', 'place mat', 'tomb', 'big top', 'gas pump', 'lockers', 'cage', 'finger', 'bleachers', 'ferris wheel', 'hairdresser chair', 'mat', 'stands', 'aquarium', 'streetcar', 'napkin', 'dummy', 'booklet', 'sand trap', 'shop', 'table cloth', 'service station', 'coffin', 'drawer', 'cages', 'slot machine', 'balcony', 'volleyball court', 'table tennis', 'control table', 'shirt', 'merchandise', 'railway', 'parterre', 'chimney', 'can', 'tanks', 'fabric', 'alga', 'system', 'map', 'greenhouse', 'mug', 'barbecue', 'trailer', 'toilet tissue', 'organ', 'dishrag', 'island', 'keyboard', 'trench', 'basket', 'steering wheel', 'pitcher', 'goal', 'bread', 'beds', 'wood', 'file cabinet', 'newspaper', 'motorboat', 'rope', 'guitar', 'rubble', 'scarf', 'barrels', 'cap', 'leaves', 'control tower', 'dashboard', 'bandstand', 'lectern', 'switch', 'baseboard', 'shower room', 'smoke', 'faucet', 'bulldozer', 'saucepan', 'shops', 'meter', 'crevasse', 'gear', 'candelabrum', 'sofa bed', 'tunnel', 'pallet', 'wire', 'kettle', 'bidet', 'baby buggy', 'music stand', 'pipe', 'cup', 'parking meter', 'ice hockey rink', 'shelter', 'weeds', 'temple', 'patty', 'ski slope', 'panel', 'wallet', 'wheel', 'towel rack', 'roundabout', 'canister', 'rod', 'soap dispenser', 'bell', 'canvas', 'box office', 'teacup', 'trellis', 'workbench', 'valley', 'toaster', 'knife', 'podium', 'ramp', 'tumble dryer', 'fireplug', 'gym shoe', 'lab bench', 'equipment', 'rocky formation', 'plastic', 'calendar', 'caravan', 'check-in-desk', 'ticket counter', 'brush', 'mill', 'covered bridge', 'bowling alley', 'hanger', 'excavator', 'trestle', 'revolving door', 'blast furnace', 'scale', 'projector', 'soap', 'locker', 'tractor', 'stretcher', 'frame', 'grating', 'alembic', 'candle', 'barrier', 'cardboard', 'cave', 'puddle', 'tarp', 'price tag', 'watchtower', 'meters', 'light bulb', 'tracks', 'hair dryer', 'skirt', 'viaduct', 'paper towel', 'coat', 'sheet', 'fire extinguisher', 'water wheel', 'pottery', 'magazine rack', 'teapot', 'microphone', 'support', 'forklift', 'canyon', 'cash register', 'leaf', 'remote control', 'soap dish', 'windshield', 'cat', 'cue', 'vent', 'videos', 'shovel', 'eaves', 'antenna', 'shipyard', 'hen', 'traffic cone', 'washing machines', 'truck crane', 'cds', 'niche', 'scoreboard', 'briefcase', 'boot', 'sweater', 'hay', 'pack', 'bottle rack', 'glacier', 'pergola', 'building materials', 'television camera', 'first floor', 'rifle', 'tennis table', 'stadium', 'safety belt', 'cover', 'dish rack', 'synthesizer', 'pumpkin', 'gutter', 'fruit stand', 'ice floe', 'handle', 'wheelchair', 'mousepad', 'diploma', 'fairground ride', 'radio', 'hotplate', 'junk', 'wheelbarrow', 'stream', 'toll plaza', 'punching bag', 'trough', 'throne', 'chair desk', 'weighbridge', 'extractor fan', 'hanging clothes', 'dish', 'alarm clock', 'ski lift', 'chain', 'garage', 'mechanical shovel', 'wine rack', 'tramway', 'treadmill', 'menu', 'block', 'well', 'witness stand', 'branch', 'duck', 'casserole', 'frying pan', 'desk organizer', 'mast', 'spectacles', 'service elevator', 'dollhouse', 'hammock', 'clothes hanging', 'photocopier', 'notepad', 'golf cart', 'footpath', 'cross', 'baptismal font', 'boiler', 'skip', 'rotisserie', 'tables', 'water mill', 'helmet', 'cover curtain', 'brick', 'table runner', 'ashtray', 'street box', 'stick', 'hangers', 'cells', 'urinal', 'centerpiece', 'portable fridge', 'dvds', 'golf club', 'skirting board', 'water cooler', 'clipboard', 'camera', 'pigeonhole', 'chips', 'food processor', 'post box', 'lid', 'drum', 'blender', 'cave entrance', 'dental chair', 'obelisk', 'canoe', 'mobile', 'monitors', 'pool ball', 'cue rack', 'baggage carts', 'shore', 'fork', 'paper filer', 'bicycle rack', 'coat rack', 'garland', 'sports bag', 'fish tank', 'towel dispenser', 'carriage', 'brochure', 'plaque', 'stringer', 'iron', 'spoon', 'flag pole', 'toilet brush', 'book stand', 'water faucet', 'ticket office', 'broom', 'dvd', 'ice bucket', 'carapace', 'tureen', 'folders', 'chess', 'root', 'sewing machine', 'model', 'pen', 'violin', 'sweatshirt', 'recycling materials', 'mitten', 'chopping board', 'mask', 'log', 'mouse', 'grill', 'hole', 'target', 'trash bag', 'chalk', 'sticks', 'balloon', 'score', 'hair spray', 'roll', 'runner', 'engine', 'inflatable glove', 'games', 'pallets', 'baskets', 'coop', 'dvd player', 'rocking horse', 'buckets', 'bread rolls', 'shawl', 'watering can', 'spotlights', 'post-it', 'bowls', 'security camera', 'runner cloth', 'lock', 'alarm', 'side', 'roulette', 'bone', 'cutlery', 'pool balls', 'wheels', 'spice rack', 'plant pots', 'towel ring', 'bread box', 'video', 'funfair', 'breads', 'tripod', 'ironing board', 'skimmer', 'hollow', 'scratching post', 'tricycle', 'file box', 'mountain pass', 'tombstones', 'cooker', 'card game', 'golf bag', 'towel paper', 'chaise lounge', 'sun', 'toilet paper holder', 'rake', 'key', 'umbrella stand', 'dartboard', 'transformer', 'fireplace utensils', 'sweatshirts', 'cellular telephone', 'tallboy', 'stapler', 'sauna', 'test tube', 'palette', 'shopping carts', 'tools', 'push button', 'star', 'roof rack', 'barbed wire', 'spray', 'ear', 'sponge', 'racket', 'tins', 'eyeglasses', 'file', 'scarfs', 'sugar bowl', 'flip flop', 'headstones', 'laptop bag', 'leash', 'climbing frame', 'suit hanger', 'floor spotlight', 'plate rack', 'sewer', 'hard drive', 'sprinkler', 'tools box', 'necklace', 'bulbs', 'steel industry', 'club', 'jack', 'door bars', 'control panel', 'hairbrush', 'napkin holder', 'office', 'smoke detector', 'utensils', 'apron', 'scissors', 'terminal', 'grinder', 'entry phone', 'newspaper stand', 'pepper shaker', 'onions', 'central processing unit', 'tape', 'bat', 'coaster', 'calculator', 'potatoes', 'luggage rack', 'salt', 'street number', 'viewpoint', 'sword', 'cd', 'rowing machine', 'plug', 'andiron', 'pepper', 'tongs', 'bonfire', 'dog dish', 'belt', 'dumbbells', 'videocassette recorder', 'hook', 'envelopes', 'shower faucet', 'watch', 'padlock', 'swimming pool ladder', 'spanners', 'gravy boat', 'notice board', 'trash bags', 'fire alarm', 'ladle', 'stethoscope', 'rocket', 'funnel', 'bowling pins', 'valve', 'thermometer', 'cups', 'spice jar', 'night light', 'soaps', 'games table', 'slotted spoon', 'reel', 'scourer', 'sleeping robe', 'desk mat', 'dumbbell', 'hammer', 'tie', 'typewriter', 'shaker', 'cheese dish', 'sea star', 'racquet', 'butane gas cylinder', 'paper weight', 'shaving brush', 'sunglasses', 'gear shift', 'towel rail', 'adding machine']
|
| 8 |
+
|
| 9 |
+
SUN_RGBD_37 = ['wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'blinds', 'desk', 'shelves', 'curtain', 'dresser', 'pillow', 'mirror', 'floor mat', 'clothes', 'ceiling', 'books', 'refridgerator', 'television', 'paper', 'towel', 'shower curtain', 'box', 'whiteboard', 'person', 'night stand', 'toilet', 'sink', 'lamp', 'bathtub', 'bag']
|
| 10 |
+
|
| 11 |
+
SCAN_37 = ['wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'blinds', 'desk', 'shelves', 'curtain', 'dresser', 'pillow', 'mirror', 'floor mat', 'clothes', 'ceiling', 'books', 'refridgerator', 'television', 'paper', 'towel', 'shower curtain', 'box', 'whiteboard', 'person', 'night stand', 'toilet', 'sink', 'lamp', 'bathtub', 'bag']
|
| 12 |
+
SCAN_40 = ['wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'blinds', 'desk', 'shelves', 'curtain', 'dresser', 'pillow', 'mirror', 'floor mat', 'clothes', 'ceiling', 'books', 'refridgerator', 'television', 'paper', 'towel', 'shower curtain', 'box', 'whiteboard', 'person', 'night stand', 'toilet', 'sink', 'lamp', 'bathtub', 'bag', 'otherstructure', 'otherfurniture', 'otherprop']
|
| 13 |
+
SCAN_20 = ["wall", "floor", "cabinet", "bed", "chair", "sofa", "table", "door", "window", "bookshelf", "picture", "counter", "desk", "curtain", "refrigerator", "shower curtain", "toilet", "sink", "bathtub", "otherfurniture"]
|
| 14 |
+
|
| 15 |
+
CITYSCAPES = ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle']
|
| 16 |
+
CITYSCAPES_THING = ["person", "rider", "car", "truck", "bus", "train", "motorcycle", "bicycle"]
|
| 17 |
+
|
| 18 |
+
BDD_SEM = ["road", "sidewalk", "building", "wall", "fence", "pole", "traffic light", "traffic sign", "vegetation", "terrain", "sky", "person", "rider", "car", "truck", "bus", "train", "motorcycle", "bicycle"]
|
| 19 |
+
BDD_PANO = ['dynamic', 'ego vehicle', 'ground', 'static', 'parking', 'rail track', 'road', 'sidewalk', 'bridge', 'building', 'fence', 'garage', 'guard rail', 'tunnel', 'wall', 'banner', 'billboard', 'lane divider', 'parking sign', 'pole', 'polegroup', 'street light', 'traffic cone', 'traffic device', 'traffic light', 'traffic sign', 'traffic sign frame', 'terrain', 'vegetation', 'sky', 'person', 'rider', 'bicycle', 'bus', 'car', 'caravan', 'motorcycle', 'trailer', 'train', 'truck']
|
| 20 |
+
|
| 21 |
+
IMAGENET_CLASSES = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "projectile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "dark glasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"]
|
| 22 |
+
|
| 23 |
+
IMAGENET_FOLDER_NAMES = ['n01440764', 'n01443537', 'n01484850', 'n01491361', 'n01494475', 'n01496331', 'n01498041', 'n01514668', 'n01514859', 'n01518878', 'n01530575', 'n01531178', 'n01532829', 'n01534433', 'n01537544', 'n01558993', 'n01560419', 'n01580077', 'n01582220', 'n01592084', 'n01601694', 'n01608432', 'n01614925', 'n01616318', 'n01622779', 'n01629819', 'n01630670', 'n01631663', 'n01632458', 'n01632777', 'n01641577', 'n01644373', 'n01644900', 'n01664065', 'n01665541', 'n01667114', 'n01667778', 'n01669191', 'n01675722', 'n01677366', 'n01682714', 'n01685808', 'n01687978', 'n01688243', 'n01689811', 'n01692333', 'n01693334', 'n01694178', 'n01695060', 'n01697457', 'n01698640', 'n01704323', 'n01728572', 'n01728920', 'n01729322', 'n01729977', 'n01734418', 'n01735189', 'n01737021', 'n01739381', 'n01740131', 'n01742172', 'n01744401', 'n01748264', 'n01749939', 'n01751748', 'n01753488', 'n01755581', 'n01756291', 'n01768244', 'n01770081', 'n01770393', 'n01773157', 'n01773549', 'n01773797', 'n01774384', 'n01774750', 'n01775062', 'n01776313', 'n01784675', 'n01795545', 'n01796340', 'n01797886', 'n01798484', 'n01806143', 'n01806567', 'n01807496', 'n01817953', 'n01818515', 'n01819313', 'n01820546', 'n01824575', 'n01828970', 'n01829413', 'n01833805', 'n01843065', 'n01843383', 'n01847000', 'n01855032', 'n01855672', 'n01860187', 'n01871265', 'n01872401', 'n01873310', 'n01877812', 'n01882714', 'n01883070', 'n01910747', 'n01914609', 'n01917289', 'n01924916', 'n01930112', 'n01943899', 'n01944390', 'n01945685', 'n01950731', 'n01955084', 'n01968897', 'n01978287', 'n01978455', 'n01980166', 'n01981276', 'n01983481', 'n01984695', 'n01985128', 'n01986214', 'n01990800', 'n02002556', 'n02002724', 'n02006656', 'n02007558', 'n02009229', 'n02009912', 'n02011460', 'n02012849', 'n02013706', 'n02017213', 'n02018207', 'n02018795', 'n02025239', 'n02027492', 'n02028035', 'n02033041', 'n02037110', 'n02051845', 'n02056570', 'n02058221', 'n02066245', 'n02071294', 'n02074367', 'n02077923', 'n02085620', 'n02085782', 'n02085936', 'n02086079', 'n02086240', 'n02086646', 'n02086910', 'n02087046', 'n02087394', 'n02088094', 'n02088238', 'n02088364', 'n02088466', 'n02088632', 'n02089078', 'n02089867', 'n02089973', 'n02090379', 'n02090622', 'n02090721', 'n02091032', 'n02091134', 'n02091244', 'n02091467', 'n02091635', 'n02091831', 'n02092002', 'n02092339', 'n02093256', 'n02093428', 'n02093647', 'n02093754', 'n02093859', 'n02093991', 'n02094114', 'n02094258', 'n02094433', 'n02095314', 'n02095570', 'n02095889', 'n02096051', 'n02096177', 'n02096294', 'n02096437', 'n02096585', 'n02097047', 'n02097130', 'n02097209', 'n02097298', 'n02097474', 'n02097658', 'n02098105', 'n02098286', 'n02098413', 'n02099267', 'n02099429', 'n02099601', 'n02099712', 'n02099849', 'n02100236', 'n02100583', 'n02100735', 'n02100877', 'n02101006', 'n02101388', 'n02101556', 'n02102040', 'n02102177', 'n02102318', 'n02102480', 'n02102973', 'n02104029', 'n02104365', 'n02105056', 'n02105162', 'n02105251', 'n02105412', 'n02105505', 'n02105641', 'n02105855', 'n02106030', 'n02106166', 'n02106382', 'n02106550', 'n02106662', 'n02107142', 'n02107312', 'n02107574', 'n02107683', 'n02107908', 'n02108000', 'n02108089', 'n02108422', 'n02108551', 'n02108915', 'n02109047', 'n02109525', 'n02109961', 'n02110063', 'n02110185', 'n02110341', 'n02110627', 'n02110806', 'n02110958', 'n02111129', 'n02111277', 'n02111500', 'n02111889', 'n02112018', 'n02112137', 'n02112350', 'n02112706', 'n02113023', 'n02113186', 'n02113624', 'n02113712', 'n02113799', 'n02113978', 'n02114367', 'n02114548', 'n02114712', 'n02114855', 'n02115641', 'n02115913', 'n02116738', 'n02117135', 'n02119022', 'n02119789', 'n02120079', 'n02120505', 'n02123045', 'n02123159', 'n02123394', 'n02123597', 'n02124075', 'n02125311', 'n02127052', 'n02128385', 'n02128757', 'n02128925', 'n02129165', 'n02129604', 'n02130308', 'n02132136', 'n02133161', 'n02134084', 'n02134418', 'n02137549', 'n02138441', 'n02165105', 'n02165456', 'n02167151', 'n02168699', 'n02169497', 'n02172182', 'n02174001', 'n02177972', 'n02190166', 'n02206856', 'n02219486', 'n02226429', 'n02229544', 'n02231487', 'n02233338', 'n02236044', 'n02256656', 'n02259212', 'n02264363', 'n02268443', 'n02268853', 'n02276258', 'n02277742', 'n02279972', 'n02280649', 'n02281406', 'n02281787', 'n02317335', 'n02319095', 'n02321529', 'n02325366', 'n02326432', 'n02328150', 'n02342885', 'n02346627', 'n02356798', 'n02361337', 'n02363005', 'n02364673', 'n02389026', 'n02391049', 'n02395406', 'n02396427', 'n02397096', 'n02398521', 'n02403003', 'n02408429', 'n02410509', 'n02412080', 'n02415577', 'n02417914', 'n02422106', 'n02422699', 'n02423022', 'n02437312', 'n02437616', 'n02441942', 'n02442845', 'n02443114', 'n02443484', 'n02444819', 'n02445715', 'n02447366', 'n02454379', 'n02457408', 'n02480495', 'n02480855', 'n02481823', 'n02483362', 'n02483708', 'n02484975', 'n02486261', 'n02486410', 'n02487347', 'n02488291', 'n02488702', 'n02489166', 'n02490219', 'n02492035', 'n02492660', 'n02493509', 'n02493793', 'n02494079', 'n02497673', 'n02500267', 'n02504013', 'n02504458', 'n02509815', 'n02510455', 'n02514041', 'n02526121', 'n02536864', 'n02606052', 'n02607072', 'n02640242', 'n02641379', 'n02643566', 'n02655020', 'n02666196', 'n02667093', 'n02669723', 'n02672831', 'n02676566', 'n02687172', 'n02690373', 'n02692877', 'n02699494', 'n02701002', 'n02704792', 'n02708093', 'n02727426', 'n02730930', 'n02747177', 'n02749479', 'n02769748', 'n02776631', 'n02777292', 'n02782093', 'n02783161', 'n02786058', 'n02787622', 'n02788148', 'n02790996', 'n02791124', 'n02791270', 'n02793495', 'n02794156', 'n02795169', 'n02797295', 'n02799071', 'n02802426', 'n02804414', 'n02804610', 'n02807133', 'n02808304', 'n02808440', 'n02814533', 'n02814860', 'n02815834', 'n02817516', 'n02823428', 'n02823750', 'n02825657', 'n02834397', 'n02835271', 'n02837789', 'n02840245', 'n02841315', 'n02843684', 'n02859443', 'n02860847', 'n02865351', 'n02869837', 'n02870880', 'n02871525', 'n02877765', 'n02879718', 'n02883205', 'n02892201', 'n02892767', 'n02894605', 'n02895154', 'n02906734', 'n02909870', 'n02910353', 'n02916936', 'n02917067', 'n02927161', 'n02930766', 'n02939185', 'n02948072', 'n02950826', 'n02951358', 'n02951585', 'n02963159', 'n02965783', 'n02966193', 'n02966687', 'n02971356', 'n02974003', 'n02977058', 'n02978881', 'n02979186', 'n02980441', 'n02981792', 'n02988304', 'n02992211', 'n02992529', 'n02999410', 'n03000134', 'n03000247', 'n03000684', 'n03014705', 'n03016953', 'n03017168', 'n03018349', 'n03026506', 'n03028079', 'n03032252', 'n03041632', 'n03042490', 'n03045698', 'n03047690', 'n03062245', 'n03063599', 'n03063689', 'n03065424', 'n03075370', 'n03085013', 'n03089624', 'n03095699', 'n03100240', 'n03109150', 'n03110669', 'n03124043', 'n03124170', 'n03125729', 'n03126707', 'n03127747', 'n03127925', 'n03131574', 'n03133878', 'n03134739', 'n03141823', 'n03146219', 'n03160309', 'n03179701', 'n03180011', 'n03187595', 'n03188531', 'n03196217', 'n03197337', 'n03201208', 'n03207743', 'n03207941', 'n03208938', 'n03216828', 'n03218198', 'n03220513', 'n03223299', 'n03240683', 'n03249569', 'n03250847', 'n03255030', 'n03259280', 'n03271574', 'n03272010', 'n03272562', 'n03290653', 'n03291819', 'n03297495', 'n03314780', 'n03325584', 'n03337140', 'n03344393', 'n03345487', 'n03347037', 'n03355925', 'n03372029', 'n03376595', 'n03379051', 'n03384352', 'n03388043', 'n03388183', 'n03388549', 'n03393912', 'n03394916', 'n03400231', 'n03404251', 'n03417042', 'n03424325', 'n03425413', 'n03443371', 'n03444034', 'n03445777', 'n03445924', 'n03447447', 'n03447721', 'n03450230', 'n03452741', 'n03457902', 'n03459775', 'n03461385', 'n03467068', 'n03476684', 'n03476991', 'n03478589', 'n03481172', 'n03482405', 'n03483316', 'n03485407', 'n03485794', 'n03492542', 'n03494278', 'n03495258', 'n03496892', 'n03498962', 'n03527444', 'n03529860', 'n03530642', 'n03532672', 'n03534580', 'n03535780', 'n03538406', 'n03544143', 'n03584254', 'n03584829', 'n03590841', 'n03594734', 'n03594945', 'n03595614', 'n03598930', 'n03599486', 'n03602883', 'n03617480', 'n03623198', 'n03627232', 'n03630383', 'n03633091', 'n03637318', 'n03642806', 'n03649909', 'n03657121', 'n03658185', 'n03661043', 'n03662601', 'n03666591', 'n03670208', 'n03673027', 'n03676483', 'n03680355', 'n03690938', 'n03691459', 'n03692522', 'n03697007', 'n03706229', 'n03709823', 'n03710193', 'n03710637', 'n03710721', 'n03717622', 'n03720891', 'n03721384', 'n03724870', 'n03729826', 'n03733131', 'n03733281', 'n03733805', 'n03742115', 'n03743016', 'n03759954', 'n03761084', 'n03763968', 'n03764736', 'n03769881', 'n03770439', 'n03770679', 'n03773504', 'n03775071', 'n03775546', 'n03776460', 'n03777568', 'n03777754', 'n03781244', 'n03782006', 'n03785016', 'n03786901', 'n03787032', 'n03788195', 'n03788365', 'n03791053', 'n03792782', 'n03792972', 'n03793489', 'n03794056', 'n03796401', 'n03803284', 'n03804744', 'n03814639', 'n03814906', 'n03825788', 'n03832673', 'n03837869', 'n03838899', 'n03840681', 'n03841143', 'n03843555', 'n03854065', 'n03857828', 'n03866082', 'n03868242', 'n03868863', 'n03871628', 'n03873416', 'n03874293', 'n03874599', 'n03876231', 'n03877472', 'n03877845', 'n03884397', 'n03887697', 'n03888257', 'n03888605', 'n03891251', 'n03891332', 'n03895866', 'n03899768', 'n03902125', 'n03903868', 'n03908618', 'n03908714', 'n03916031', 'n03920288', 'n03924679', 'n03929660', 'n03929855', 'n03930313', 'n03930630', 'n03933933', 'n03935335', 'n03937543', 'n03938244', 'n03942813', 'n03944341', 'n03947888', 'n03950228', 'n03954731', 'n03956157', 'n03958227', 'n03961711', 'n03967562', 'n03970156', 'n03976467', 'n03976657', 'n03977966', 'n03980874', 'n03982430', 'n03983396', 'n03991062', 'n03992509', 'n03995372', 'n03998194', 'n04004767', 'n04005630', 'n04008634', 'n04009552', 'n04019541', 'n04023962', 'n04026417', 'n04033901', 'n04033995', 'n04037443', 'n04039381', 'n04040759', 'n04041544', 'n04044716', 'n04049303', 'n04065272', 'n04067472', 'n04069434', 'n04070727', 'n04074963', 'n04081281', 'n04086273', 'n04090263', 'n04099969', 'n04111531', 'n04116512', 'n04118538', 'n04118776', 'n04120489', 'n04125021', 'n04127249', 'n04131690', 'n04133789', 'n04136333', 'n04141076', 'n04141327', 'n04141975', 'n04146614', 'n04147183', 'n04149813', 'n04152593', 'n04153751', 'n04154565', 'n04162706', 'n04179913', 'n04192698', 'n04200800', 'n04201297', 'n04204238', 'n04204347', 'n04208210', 'n04209133', 'n04209239', 'n04228054', 'n04229816', 'n04235860', 'n04238763', 'n04239074', 'n04243546', 'n04251144', 'n04252077', 'n04252225', 'n04254120', 'n04254680', 'n04254777', 'n04258138', 'n04259630', 'n04263257', 'n04264628', 'n04265275', 'n04266014', 'n04270147', 'n04273569', 'n04275548', 'n04277352', 'n04285008', 'n04286575', 'n04296562', 'n04310018', 'n04311004', 'n04311174', 'n04317175', 'n04325704', 'n04326547', 'n04328186', 'n04330267', 'n04332243', 'n04335435', 'n04336792', 'n04344873', 'n04346328', 'n04347754', 'n04350905', 'n04355338', 'n04355933', 'n04356056', 'n04357314', 'n04366367', 'n04367480', 'n04370456', 'n04371430', 'n04371774', 'n04372370', 'n04376876', 'n04380533', 'n04389033', 'n04392985', 'n04398044', 'n04399382', 'n04404412', 'n04409515', 'n04417672', 'n04418357', 'n04423845', 'n04428191', 'n04429376', 'n04435653', 'n04442312', 'n04443257', 'n04447861', 'n04456115', 'n04458633', 'n04461696', 'n04462240', 'n04465501', 'n04467665', 'n04476259', 'n04479046', 'n04482393', 'n04483307', 'n04485082', 'n04486054', 'n04487081', 'n04487394', 'n04493381', 'n04501370', 'n04505470', 'n04507155', 'n04509417', 'n04515003', 'n04517823', 'n04522168', 'n04523525', 'n04525038', 'n04525305', 'n04532106', 'n04532670', 'n04536866', 'n04540053', 'n04542943', 'n04548280', 'n04548362', 'n04550184', 'n04552348', 'n04553703', 'n04554684', 'n04557648', 'n04560804', 'n04562935', 'n04579145', 'n04579432', 'n04584207', 'n04589890', 'n04590129', 'n04591157', 'n04591713', 'n04592741', 'n04596742', 'n04597913', 'n04599235', 'n04604644', 'n04606251', 'n04612504', 'n04613696', 'n06359193', 'n06596364', 'n06785654', 'n06794110', 'n06874185', 'n07248320', 'n07565083', 'n07579787', 'n07583066', 'n07584110', 'n07590611', 'n07613480', 'n07614500', 'n07615774', 'n07684084', 'n07693725', 'n07695742', 'n07697313', 'n07697537', 'n07711569', 'n07714571', 'n07714990', 'n07715103', 'n07716358', 'n07716906', 'n07717410', 'n07717556', 'n07718472', 'n07718747', 'n07720875', 'n07730033', 'n07734744', 'n07742313', 'n07745940', 'n07747607', 'n07749582', 'n07753113', 'n07753275', 'n07753592', 'n07754684', 'n07760859', 'n07768694', 'n07802026', 'n07831146', 'n07836838', 'n07860988', 'n07871810', 'n07873807', 'n07875152', 'n07880968', 'n07892512', 'n07920052', 'n07930864', 'n07932039', 'n09193705', 'n09229709', 'n09246464', 'n09256479', 'n09288635', 'n09332890', 'n09399592', 'n09421951', 'n09428293', 'n09468604', 'n09472597', 'n09835506', 'n10148035', 'n10565667', 'n11879895', 'n11939491', 'n12057211', 'n12144580', 'n12267677', 'n12620546', 'n12768682', 'n12985857', 'n12998815', 'n13037406', 'n13040303', 'n13044778', 'n13052670', 'n13054560', 'n13133613', 'n15075141']
|
| 24 |
+
|
| 25 |
+
PREDICATES = [
|
| 26 |
+
'over',
|
| 27 |
+
'in front of',
|
| 28 |
+
'beside',
|
| 29 |
+
'on',
|
| 30 |
+
'in',
|
| 31 |
+
'attached to',
|
| 32 |
+
'hanging from',
|
| 33 |
+
'on back of',
|
| 34 |
+
'falling off',
|
| 35 |
+
'going down',
|
| 36 |
+
'painted on',
|
| 37 |
+
'walking on',
|
| 38 |
+
'running on',
|
| 39 |
+
'crossing',
|
| 40 |
+
'standing on',
|
| 41 |
+
'lying on',
|
| 42 |
+
'sitting on',
|
| 43 |
+
'flying over',
|
| 44 |
+
'jumping over',
|
| 45 |
+
'jumping from',
|
| 46 |
+
'wearing',
|
| 47 |
+
'holding',
|
| 48 |
+
'carrying',
|
| 49 |
+
'looking at',
|
| 50 |
+
'guiding',
|
| 51 |
+
'kissing',
|
| 52 |
+
'eating',
|
| 53 |
+
'drinking',
|
| 54 |
+
'feeding',
|
| 55 |
+
'biting',
|
| 56 |
+
'catching',
|
| 57 |
+
'picking',
|
| 58 |
+
'playing with',
|
| 59 |
+
'chasing',
|
| 60 |
+
'climbing',
|
| 61 |
+
'cleaning',
|
| 62 |
+
'playing',
|
| 63 |
+
'touching',
|
| 64 |
+
'pushing',
|
| 65 |
+
'pulling',
|
| 66 |
+
'opening',
|
| 67 |
+
'cooking',
|
| 68 |
+
'talking to',
|
| 69 |
+
'throwing',
|
| 70 |
+
'slicing',
|
| 71 |
+
'driving',
|
| 72 |
+
'riding',
|
| 73 |
+
'parked on',
|
| 74 |
+
'driving on',
|
| 75 |
+
'about to hit',
|
| 76 |
+
'kicking',
|
| 77 |
+
'swinging',
|
| 78 |
+
'entering',
|
| 79 |
+
'exiting',
|
| 80 |
+
'enclosing',
|
| 81 |
+
'leaning on',
|
| 82 |
+
]
|
| 83 |
+
|
| 84 |
+
IMAGENET_DEFAULT_TEMPLATES = [
|
| 85 |
+
'{}.',
|
| 86 |
+
'a bad photo of a {}.',
|
| 87 |
+
'a photo of many {}.',
|
| 88 |
+
'a sculpture of a {}.',
|
| 89 |
+
'a photo of the hard to see {}.',
|
| 90 |
+
'a low resolution photo of the {}.',
|
| 91 |
+
'a rendering of a {}.',
|
| 92 |
+
'graffiti of a {}.',
|
| 93 |
+
'a bad photo of the {}.',
|
| 94 |
+
'a cropped photo of the {}.',
|
| 95 |
+
'a tattoo of a {}.',
|
| 96 |
+
'the embroidered {}.',
|
| 97 |
+
'a photo of a hard to see {}.',
|
| 98 |
+
'a bright photo of a {}.',
|
| 99 |
+
'a photo of a clean {}.',
|
| 100 |
+
'a photo of a dirty {}.',
|
| 101 |
+
'a dark photo of the {}.',
|
| 102 |
+
'a drawing of a {}.',
|
| 103 |
+
'a photo of my {}.',
|
| 104 |
+
'the plastic {}.',
|
| 105 |
+
'a photo of the cool {}.',
|
| 106 |
+
'a close-up photo of a {}.',
|
| 107 |
+
'a black and white photo of the {}.',
|
| 108 |
+
'a painting of the {}.',
|
| 109 |
+
'a painting of a {}.',
|
| 110 |
+
'a pixelated photo of the {}.',
|
| 111 |
+
'a sculpture of the {}.',
|
| 112 |
+
'a bright photo of the {}.',
|
| 113 |
+
'a cropped photo of a {}.',
|
| 114 |
+
'a plastic {}.',
|
| 115 |
+
'a photo of the dirty {}.',
|
| 116 |
+
'a jpeg corrupted photo of a {}.',
|
| 117 |
+
'a blurry photo of the {}.',
|
| 118 |
+
'a photo of the {}.',
|
| 119 |
+
'a good photo of the {}.',
|
| 120 |
+
'a rendering of the {}.',
|
| 121 |
+
'a {} in a video game.',
|
| 122 |
+
'a photo of one {}.',
|
| 123 |
+
'a doodle of a {}.',
|
| 124 |
+
'a close-up photo of the {}.',
|
| 125 |
+
'a photo of a {}.',
|
| 126 |
+
'the origami {}.',
|
| 127 |
+
'the {} in a video game.',
|
| 128 |
+
'a sketch of a {}.',
|
| 129 |
+
'a doodle of the {}.',
|
| 130 |
+
'a origami {}.',
|
| 131 |
+
'a low resolution photo of a {}.',
|
| 132 |
+
'the toy {}.',
|
| 133 |
+
'a rendition of the {}.',
|
| 134 |
+
'a photo of the clean {}.',
|
| 135 |
+
'a photo of a large {}.',
|
| 136 |
+
'a rendition of a {}.',
|
| 137 |
+
'a photo of a nice {}.',
|
| 138 |
+
'a photo of a weird {}.',
|
| 139 |
+
'a blurry photo of a {}.',
|
| 140 |
+
'a cartoon {}.',
|
| 141 |
+
'art of a {}.',
|
| 142 |
+
'a sketch of the {}.',
|
| 143 |
+
'a embroidered {}.',
|
| 144 |
+
'a pixelated photo of a {}.',
|
| 145 |
+
'itap of the {}.',
|
| 146 |
+
'a jpeg corrupted photo of the {}.',
|
| 147 |
+
'a good photo of a {}.',
|
| 148 |
+
'a plushie {}.',
|
| 149 |
+
'a photo of the nice {}.',
|
| 150 |
+
'a photo of the small {}.',
|
| 151 |
+
'a photo of the weird {}.',
|
| 152 |
+
'the cartoon {}.',
|
| 153 |
+
'art of the {}.',
|
| 154 |
+
'a drawing of the {}.',
|
| 155 |
+
'a photo of the large {}.',
|
| 156 |
+
'a black and white photo of a {}.',
|
| 157 |
+
'the plushie {}.',
|
| 158 |
+
'a dark photo of a {}.',
|
| 159 |
+
'itap of a {}.',
|
| 160 |
+
'graffiti of the {}.',
|
| 161 |
+
'a toy {}.',
|
| 162 |
+
'itap of my {}.',
|
| 163 |
+
'a photo of a cool {}.',
|
| 164 |
+
'a photo of a small {}.',
|
| 165 |
+
'a tattoo of the {}.',
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
IMAGENET_SIMPLE_TEMPLATES = [
|
| 169 |
+
'a photo of {}.',
|
| 170 |
+
]
|
| 171 |
+
|
| 172 |
+
PASCAL_CLASSES = [
|
| 173 |
+
"aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat",
|
| 174 |
+
"chair", "cow", "diningtable", "dog", "horse", "motorbike", "person",
|
| 175 |
+
"pottedplant", "sheep", "sofa", "train", "tvmonitor"
|
| 176 |
+
]
|
modeling_minicpmv.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
import json
|
| 4 |
+
import torch
|
| 5 |
+
import torchvision
|
| 6 |
+
|
| 7 |
+
from threading import Thread
|
| 8 |
+
from copy import deepcopy
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from transformers import AutoProcessor, Qwen2PreTrainedModel, Qwen2ForCausalLM, TextIteratorStreamer, Owlv2ForObjectDetection
|
| 11 |
+
from .constants import ADE20K_847, IMAGENET_CLASSES
|
| 12 |
+
|
| 13 |
+
from .configuration_minicpm import MiniCPMVConfig
|
| 14 |
+
from .modeling_navit_siglip import SiglipVisionTransformer
|
| 15 |
+
from .resampler import Resampler
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MiniCPMVPreTrainedModel(Qwen2PreTrainedModel):
|
| 20 |
+
config_class = MiniCPMVConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class MiniCPMV(MiniCPMVPreTrainedModel):
|
| 24 |
+
def __init__(self, config):
|
| 25 |
+
super().__init__(config)
|
| 26 |
+
self.llm = Qwen2ForCausalLM(config)
|
| 27 |
+
self.vpm = self.init_vision_module()
|
| 28 |
+
self.od_model = self.init_od_model()
|
| 29 |
+
self.od_processor = self.init_od_processor()
|
| 30 |
+
self.vision_dim = self.vpm.embed_dim
|
| 31 |
+
self.embed_dim = self.llm.config.hidden_size
|
| 32 |
+
self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
|
| 33 |
+
self.processor = None
|
| 34 |
+
|
| 35 |
+
self.terminators = ['<|im_end|>', '<|endoftext|>']
|
| 36 |
+
self._generate = self.generate
|
| 37 |
+
|
| 38 |
+
def init_vision_module(self):
|
| 39 |
+
# same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
|
| 40 |
+
if self.config._attn_implementation == 'flash_attention_2':
|
| 41 |
+
self.config.vision_config._attn_implementation = 'flash_attention_2'
|
| 42 |
+
else:
|
| 43 |
+
# not suport sdpa
|
| 44 |
+
self.config.vision_config._attn_implementation = 'eager'
|
| 45 |
+
model = SiglipVisionTransformer(self.config.vision_config)
|
| 46 |
+
if self.config.drop_vision_last_layer:
|
| 47 |
+
model.encoder.layers = model.encoder.layers[:-1]
|
| 48 |
+
|
| 49 |
+
setattr(model, 'embed_dim', model.embeddings.embed_dim)
|
| 50 |
+
setattr(model, 'patch_size', model.embeddings.patch_size)
|
| 51 |
+
|
| 52 |
+
return model
|
| 53 |
+
|
| 54 |
+
def init_od_model(self):
|
| 55 |
+
# google/owlv2-base-patch16-ensemble
|
| 56 |
+
od_model = Owlv2ForObjectDetection.from_pretrained(self.config.od_model_name).cuda()
|
| 57 |
+
return od_model
|
| 58 |
+
|
| 59 |
+
def init_od_processor(self):
|
| 60 |
+
# google/owlv2-base-patch16-ensemble
|
| 61 |
+
od_processor = AutoProcessor.from_pretrained(self.config.od_processor_name)
|
| 62 |
+
return od_processor
|
| 63 |
+
|
| 64 |
+
def init_resampler(self, embed_dim, vision_dim):
|
| 65 |
+
return Resampler(
|
| 66 |
+
num_queries=self.config.query_num,
|
| 67 |
+
embed_dim=embed_dim,
|
| 68 |
+
num_heads=embed_dim // 128,
|
| 69 |
+
kv_dim=vision_dim,
|
| 70 |
+
adaptive=True
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def get_input_embeddings(self):
|
| 74 |
+
return self.llm.get_input_embeddings()
|
| 75 |
+
|
| 76 |
+
def set_input_embeddings(self, value):
|
| 77 |
+
self.llm.embed_tokens = value
|
| 78 |
+
|
| 79 |
+
def get_output_embeddings(self):
|
| 80 |
+
return self.llm.lm_head
|
| 81 |
+
|
| 82 |
+
def set_output_embeddings(self, new_embeddings):
|
| 83 |
+
self.llm.lm_head = new_embeddings
|
| 84 |
+
|
| 85 |
+
def set_decoder(self, decoder):
|
| 86 |
+
self.llm = decoder
|
| 87 |
+
|
| 88 |
+
def get_decoder(self):
|
| 89 |
+
return self.llm
|
| 90 |
+
|
| 91 |
+
def get_vllm_embedding(self, data):
|
| 92 |
+
if 'vision_hidden_states' not in data:
|
| 93 |
+
dtype = self.llm.model.embed_tokens.weight.dtype
|
| 94 |
+
device = self.llm.model.embed_tokens.weight.device
|
| 95 |
+
tgt_sizes = data['tgt_sizes']
|
| 96 |
+
pixel_values_list = data['pixel_values']
|
| 97 |
+
vision_hidden_states = []
|
| 98 |
+
all_pixel_values = []
|
| 99 |
+
img_cnt = []
|
| 100 |
+
for pixel_values in pixel_values_list:
|
| 101 |
+
img_cnt.append(len(pixel_values))
|
| 102 |
+
all_pixel_values.extend([i.flatten(end_dim=1).permute(1, 0) for i in pixel_values])
|
| 103 |
+
|
| 104 |
+
# exist image
|
| 105 |
+
if all_pixel_values:
|
| 106 |
+
tgt_sizes = [tgt_size for tgt_size in tgt_sizes if isinstance(tgt_size, torch.Tensor)]
|
| 107 |
+
tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
|
| 108 |
+
|
| 109 |
+
max_patches = torch.max(tgt_sizes[:, 0] * tgt_sizes[:, 1])
|
| 110 |
+
|
| 111 |
+
all_pixel_values = torch.nn.utils.rnn.pad_sequence(all_pixel_values, batch_first=True,
|
| 112 |
+
padding_value=0.0)
|
| 113 |
+
B, L, _ = all_pixel_values.shape
|
| 114 |
+
all_pixel_values = all_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
|
| 115 |
+
|
| 116 |
+
patch_attn_mask = torch.zeros((B, 1, max_patches), dtype=torch.bool, device=device)
|
| 117 |
+
for i in range(B):
|
| 118 |
+
patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
|
| 119 |
+
|
| 120 |
+
vision_batch_size = self.config.vision_batch_size
|
| 121 |
+
all_pixel_values = all_pixel_values.type(dtype)
|
| 122 |
+
if B > vision_batch_size:
|
| 123 |
+
hs = []
|
| 124 |
+
for i in range(0, B, vision_batch_size):
|
| 125 |
+
start_idx = i
|
| 126 |
+
end_idx = i + vision_batch_size
|
| 127 |
+
tmp_hs = self.vpm(all_pixel_values[start_idx:end_idx], patch_attention_mask=patch_attn_mask[start_idx:end_idx], tgt_sizes=tgt_sizes[start_idx:end_idx]).last_hidden_state
|
| 128 |
+
hs.append(tmp_hs)
|
| 129 |
+
vision_embedding = torch.cat(hs, dim=0)
|
| 130 |
+
else:
|
| 131 |
+
vision_embedding = self.vpm(all_pixel_values, patch_attention_mask=patch_attn_mask, tgt_sizes=tgt_sizes).last_hidden_state
|
| 132 |
+
vision_embedding = self.resampler(vision_embedding, tgt_sizes)
|
| 133 |
+
|
| 134 |
+
start = 0
|
| 135 |
+
for pixel_values in pixel_values_list:
|
| 136 |
+
img_cnt = len(pixel_values)
|
| 137 |
+
if img_cnt > 0:
|
| 138 |
+
vision_hidden_states.append(vision_embedding[start: start + img_cnt])
|
| 139 |
+
start += img_cnt
|
| 140 |
+
else:
|
| 141 |
+
vision_hidden_states.append([])
|
| 142 |
+
else: # no image
|
| 143 |
+
if self.training:
|
| 144 |
+
dummy_image = torch.zeros(
|
| 145 |
+
(1, 3, 224, 224),
|
| 146 |
+
device=device, dtype=dtype
|
| 147 |
+
)
|
| 148 |
+
tgt_sizes = torch.Tensor([[(224 // self.config.patch_size), math.ceil(224 / self.config.patch_size)]]).type(torch.int32)
|
| 149 |
+
dummy_feature = self.resampler(self.vpm(dummy_image).last_hidden_state, tgt_sizes)
|
| 150 |
+
else:
|
| 151 |
+
dummy_feature = []
|
| 152 |
+
for _ in range(len(pixel_values_list)):
|
| 153 |
+
vision_hidden_states.append(dummy_feature)
|
| 154 |
+
|
| 155 |
+
else:
|
| 156 |
+
vision_hidden_states = data['vision_hidden_states']
|
| 157 |
+
|
| 158 |
+
if hasattr(self.llm.config, 'scale_emb'):
|
| 159 |
+
vllm_embedding = self.llm.model.embed_tokens(data['input_ids']) * self.llm.config.scale_emb
|
| 160 |
+
else:
|
| 161 |
+
vllm_embedding = self.llm.model.embed_tokens(data['input_ids'])
|
| 162 |
+
|
| 163 |
+
new_vllm_embedding = vllm_embedding.clone()
|
| 164 |
+
|
| 165 |
+
vision_hidden_states = [i.type(vllm_embedding.dtype) if isinstance(
|
| 166 |
+
i, torch.Tensor) else i for i in vision_hidden_states]
|
| 167 |
+
|
| 168 |
+
bs = len(data['input_ids'])
|
| 169 |
+
for i in range(bs):
|
| 170 |
+
cur_vs_hs = vision_hidden_states[i]
|
| 171 |
+
if len(cur_vs_hs) > 0:
|
| 172 |
+
cur_vllm_emb = vllm_embedding[i]
|
| 173 |
+
cur_image_bound = data['image_bound'][i]
|
| 174 |
+
if len(cur_image_bound) > 0:
|
| 175 |
+
image_indices = torch.stack(
|
| 176 |
+
[torch.arange(r[0], r[1], dtype=torch.long) for r in cur_image_bound]
|
| 177 |
+
).to(vllm_embedding.device)
|
| 178 |
+
|
| 179 |
+
new_vllm_embedding[i] = cur_vllm_emb.scatter(0, image_indices.view(-1, 1).repeat(1, cur_vllm_emb.shape[-1]),
|
| 180 |
+
cur_vs_hs.view(-1, cur_vs_hs.shape[-1]))
|
| 181 |
+
elif self.training:
|
| 182 |
+
new_vllm_embedding[i] += cur_vs_hs[0].mean() * 0
|
| 183 |
+
|
| 184 |
+
return new_vllm_embedding, vision_hidden_states
|
| 185 |
+
|
| 186 |
+
def forward(self, data, **kwargs):
|
| 187 |
+
vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
|
| 188 |
+
position_ids = data["position_ids"]
|
| 189 |
+
if position_ids.dtype != torch.int64:
|
| 190 |
+
position_ids = position_ids.long()
|
| 191 |
+
|
| 192 |
+
for key in ['input_ids', 'inputs_embeds', 'position_ids']:
|
| 193 |
+
if key in kwargs:
|
| 194 |
+
del kwargs[key]
|
| 195 |
+
|
| 196 |
+
return self.llm(
|
| 197 |
+
input_ids=None,
|
| 198 |
+
position_ids=position_ids,
|
| 199 |
+
inputs_embeds=vllm_embedding,
|
| 200 |
+
**kwargs
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def _decode(self, inputs_embeds, tokenizer, attention_mask, decode_text=False, **kwargs):
|
| 204 |
+
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
|
| 205 |
+
output = self.llm.generate(
|
| 206 |
+
inputs_embeds=inputs_embeds,
|
| 207 |
+
pad_token_id=0,
|
| 208 |
+
eos_token_id=terminators,
|
| 209 |
+
attention_mask=attention_mask,
|
| 210 |
+
**kwargs
|
| 211 |
+
)
|
| 212 |
+
if decode_text:
|
| 213 |
+
return self._decode_text(output, tokenizer)
|
| 214 |
+
return output
|
| 215 |
+
|
| 216 |
+
def _decode_stream(self, inputs_embeds, tokenizer, **kwargs):
|
| 217 |
+
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
|
| 218 |
+
streamer = TextIteratorStreamer(tokenizer=tokenizer)
|
| 219 |
+
generation_kwargs = {
|
| 220 |
+
'inputs_embeds': inputs_embeds,
|
| 221 |
+
'pad_token_id': 0,
|
| 222 |
+
'eos_token_id': terminators,
|
| 223 |
+
'streamer': streamer
|
| 224 |
+
}
|
| 225 |
+
generation_kwargs.update(kwargs)
|
| 226 |
+
|
| 227 |
+
thread = Thread(target=self.llm.generate, kwargs=generation_kwargs)
|
| 228 |
+
thread.start()
|
| 229 |
+
|
| 230 |
+
return streamer
|
| 231 |
+
|
| 232 |
+
def _decode_text(self, result_ids, tokenizer):
|
| 233 |
+
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
|
| 234 |
+
result_text = []
|
| 235 |
+
for result in result_ids:
|
| 236 |
+
result = result[result != 0]
|
| 237 |
+
if result[0] == tokenizer.bos_id:
|
| 238 |
+
result = result[1:]
|
| 239 |
+
if result[-1] in terminators:
|
| 240 |
+
result = result[:-1]
|
| 241 |
+
result_text.append(tokenizer.decode(result).strip())
|
| 242 |
+
return result_text
|
| 243 |
+
|
| 244 |
+
def generate(
|
| 245 |
+
self,
|
| 246 |
+
input_ids=None,
|
| 247 |
+
pixel_values=None,
|
| 248 |
+
tgt_sizes=None,
|
| 249 |
+
image_bound=None,
|
| 250 |
+
attention_mask=None,
|
| 251 |
+
tokenizer=None,
|
| 252 |
+
vision_hidden_states=None,
|
| 253 |
+
return_vision_hidden_states=False,
|
| 254 |
+
stream=False,
|
| 255 |
+
decode_text=False,
|
| 256 |
+
**kwargs
|
| 257 |
+
):
|
| 258 |
+
assert input_ids is not None
|
| 259 |
+
assert len(input_ids) == len(pixel_values)
|
| 260 |
+
|
| 261 |
+
model_inputs = {
|
| 262 |
+
"input_ids": input_ids,
|
| 263 |
+
"image_bound": image_bound,
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
if vision_hidden_states is None:
|
| 267 |
+
model_inputs["pixel_values"] = pixel_values
|
| 268 |
+
model_inputs['tgt_sizes'] = tgt_sizes
|
| 269 |
+
else:
|
| 270 |
+
model_inputs["vision_hidden_states"] = vision_hidden_states
|
| 271 |
+
|
| 272 |
+
with torch.inference_mode():
|
| 273 |
+
(
|
| 274 |
+
model_inputs["inputs_embeds"],
|
| 275 |
+
vision_hidden_states,
|
| 276 |
+
) = self.get_vllm_embedding(model_inputs)
|
| 277 |
+
|
| 278 |
+
if stream:
|
| 279 |
+
result = self._decode_stream(model_inputs["inputs_embeds"], tokenizer, **kwargs)
|
| 280 |
+
else:
|
| 281 |
+
result = self._decode(model_inputs["inputs_embeds"], tokenizer, attention_mask, decode_text=decode_text, **kwargs)
|
| 282 |
+
|
| 283 |
+
if return_vision_hidden_states:
|
| 284 |
+
return result, vision_hidden_states
|
| 285 |
+
|
| 286 |
+
return result
|
| 287 |
+
|
| 288 |
+
@staticmethod
|
| 289 |
+
def box2string(box):
|
| 290 |
+
out = '['
|
| 291 |
+
for i, x in enumerate(box):
|
| 292 |
+
out += f"{round(x.item(), 2):.2f}"
|
| 293 |
+
if i != len(box) - 1: out += ', '
|
| 294 |
+
out += ']'
|
| 295 |
+
return out
|
| 296 |
+
|
| 297 |
+
def make_od_prompt(self, od_result):
|
| 298 |
+
od_scores = od_result['scores']
|
| 299 |
+
od_index = torch.where(od_scores >= 0.5)
|
| 300 |
+
od_boxes = od_result['boxes'][od_index] / 490
|
| 301 |
+
od_labels = [(ADE20K_847 + IMAGENET_CLASSES)[ind] for ind in od_result['labels'][od_index]]
|
| 302 |
+
|
| 303 |
+
if len(od_boxes) != 0:
|
| 304 |
+
verbalization_od = 'The image includes bounding box coordinates and their objects: '
|
| 305 |
+
for i, (box, label) in enumerate(zip(od_boxes, od_labels)):
|
| 306 |
+
verbalization_od += f'{self.box2string(box)} {label}'
|
| 307 |
+
if i != len(od_boxes) - 1: verbalization_od += ', and '
|
| 308 |
+
verbalization_od += '.'
|
| 309 |
+
else:
|
| 310 |
+
verbalization_od = ''
|
| 311 |
+
return verbalization_od, od_boxes, od_labels
|
| 312 |
+
|
| 313 |
+
def od_to_prompt(self, image):
|
| 314 |
+
|
| 315 |
+
od_inputs = self.od_processor(text=[ADE20K_847 + IMAGENET_CLASSES], images=[image], return_tensors="pt")
|
| 316 |
+
|
| 317 |
+
# OWOD Outputs
|
| 318 |
+
with torch.inference_mode():
|
| 319 |
+
self.od_model.eval()
|
| 320 |
+
od_results = self.od_processor.post_process_object_detection(
|
| 321 |
+
self.od_model(**{k: v.to(self.device) for k, v in od_inputs.items()}),
|
| 322 |
+
threshold=0.1,
|
| 323 |
+
target_sizes=[(490, 490)])
|
| 324 |
+
|
| 325 |
+
verbalization_od, od_boxes, od_labels = self.make_od_prompt(od_result[0])
|
| 326 |
+
|
| 327 |
+
return verbalization_od
|
| 328 |
+
|
| 329 |
+
def chat(
|
| 330 |
+
self,
|
| 331 |
+
image,
|
| 332 |
+
msgs,
|
| 333 |
+
tokenizer,
|
| 334 |
+
processor=None,
|
| 335 |
+
vision_hidden_states=None,
|
| 336 |
+
max_new_tokens=2048,
|
| 337 |
+
min_new_tokens=0,
|
| 338 |
+
sampling=True,
|
| 339 |
+
max_inp_length=8192,
|
| 340 |
+
system_prompt='',
|
| 341 |
+
stream=False,
|
| 342 |
+
max_slice_nums=None,
|
| 343 |
+
use_image_id=None,
|
| 344 |
+
**kwargs
|
| 345 |
+
):
|
| 346 |
+
if isinstance(msgs[0], list):
|
| 347 |
+
batched = True
|
| 348 |
+
else:
|
| 349 |
+
batched = False
|
| 350 |
+
msgs_list = msgs
|
| 351 |
+
images_list = image
|
| 352 |
+
|
| 353 |
+
if batched is False:
|
| 354 |
+
images_list, msgs_list = [images_list], [msgs_list]
|
| 355 |
+
else:
|
| 356 |
+
assert images_list is None, "Please integrate image to msgs when using batch inference."
|
| 357 |
+
images_list = [None] * len(msgs_list)
|
| 358 |
+
assert len(images_list) == len(msgs_list), "The batch dim of images_list and msgs_list should be the same."
|
| 359 |
+
|
| 360 |
+
if processor is None:
|
| 361 |
+
if self.processor is None:
|
| 362 |
+
self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
|
| 363 |
+
processor = self.processor
|
| 364 |
+
|
| 365 |
+
assert self.config.query_num == processor.image_processor.image_feature_size, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
|
| 366 |
+
assert self.config.patch_size == processor.image_processor.patch_size, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
|
| 367 |
+
assert self.config.use_image_id == processor.image_processor.use_image_id, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
|
| 368 |
+
assert self.config.slice_config.max_slice_nums == processor.image_processor.max_slice_nums, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
|
| 369 |
+
assert self.config.slice_mode == processor.image_processor.slice_mode, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
|
| 370 |
+
|
| 371 |
+
prompts_lists = []
|
| 372 |
+
input_images_lists = []
|
| 373 |
+
for image, msgs in zip(images_list, msgs_list):
|
| 374 |
+
if isinstance(msgs, str):
|
| 375 |
+
msgs = json.loads(msgs)
|
| 376 |
+
copy_msgs = deepcopy(msgs)
|
| 377 |
+
|
| 378 |
+
assert len(msgs) > 0, "msgs is empty"
|
| 379 |
+
assert sampling or not stream, "if use stream mode, make sure sampling=True"
|
| 380 |
+
|
| 381 |
+
if image is not None and isinstance(copy_msgs[0]["content"], str):
|
| 382 |
+
copy_msgs[0]["content"] = [image, copy_msgs[0]["content"]]
|
| 383 |
+
|
| 384 |
+
images = []
|
| 385 |
+
for i, msg in enumerate(copy_msgs):
|
| 386 |
+
role = msg["role"]
|
| 387 |
+
content = msg["content"]
|
| 388 |
+
assert role in ["user", "assistant"]
|
| 389 |
+
if i == 0:
|
| 390 |
+
assert role == "user", "The role of first msg should be user"
|
| 391 |
+
if isinstance(content, str):
|
| 392 |
+
content = [content]
|
| 393 |
+
cur_msgs = []
|
| 394 |
+
for c in content:
|
| 395 |
+
if isinstance(c, Image.Image):
|
| 396 |
+
images.append(c)
|
| 397 |
+
cur_msgs.append("(<image>./</image>)")
|
| 398 |
+
cur_msgs.append(self.od_to_prompt(c))
|
| 399 |
+
elif isinstance(c, str):
|
| 400 |
+
cur_msgs.append(c)
|
| 401 |
+
msg["content"] = "\n".join(cur_msgs)
|
| 402 |
+
|
| 403 |
+
if system_prompt:
|
| 404 |
+
sys_msg = {'role': 'system', 'content': system_prompt}
|
| 405 |
+
copy_msgs = [sys_msg] + copy_msgs
|
| 406 |
+
|
| 407 |
+
prompts_lists.append(processor.tokenizer.apply_chat_template(copy_msgs, tokenize=False, add_generation_prompt=True))
|
| 408 |
+
input_images_lists.append(images)
|
| 409 |
+
|
| 410 |
+
inputs = processor(
|
| 411 |
+
prompts_lists,
|
| 412 |
+
input_images_lists,
|
| 413 |
+
max_slice_nums=max_slice_nums,
|
| 414 |
+
use_image_id=use_image_id,
|
| 415 |
+
return_tensors="pt",
|
| 416 |
+
max_length=max_inp_length
|
| 417 |
+
).to(self.device)
|
| 418 |
+
|
| 419 |
+
if sampling:
|
| 420 |
+
generation_config = {
|
| 421 |
+
"top_p": 0.8,
|
| 422 |
+
"top_k": 100,
|
| 423 |
+
"temperature": 0.7,
|
| 424 |
+
"do_sample": True,
|
| 425 |
+
"repetition_penalty": 1.05
|
| 426 |
+
}
|
| 427 |
+
else:
|
| 428 |
+
generation_config = {
|
| 429 |
+
"num_beams": 3,
|
| 430 |
+
"repetition_penalty": 1.2,
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
if min_new_tokens > 0:
|
| 434 |
+
generation_config['min_new_tokens'] = min_new_tokens
|
| 435 |
+
|
| 436 |
+
generation_config.update(
|
| 437 |
+
(k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
inputs.pop("image_sizes")
|
| 441 |
+
with torch.inference_mode():
|
| 442 |
+
res = self.generate(
|
| 443 |
+
**inputs,
|
| 444 |
+
tokenizer=tokenizer,
|
| 445 |
+
max_new_tokens=max_new_tokens,
|
| 446 |
+
vision_hidden_states=vision_hidden_states,
|
| 447 |
+
stream=stream,
|
| 448 |
+
decode_text=True,
|
| 449 |
+
**generation_config
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
if stream:
|
| 453 |
+
def stream_gen():
|
| 454 |
+
for text in res:
|
| 455 |
+
for term in self.terminators:
|
| 456 |
+
text = text.replace(term, '')
|
| 457 |
+
yield text
|
| 458 |
+
return stream_gen()
|
| 459 |
+
|
| 460 |
+
else:
|
| 461 |
+
if batched:
|
| 462 |
+
answer = res
|
| 463 |
+
else:
|
| 464 |
+
answer = res[0]
|
| 465 |
+
return answer
|
resampler.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import partial
|
| 2 |
+
from typing import Optional, Tuple
|
| 3 |
+
import numpy as np
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from torch.nn.functional import *
|
| 11 |
+
from torch.nn.modules.activation import *
|
| 12 |
+
from torch.nn.init import trunc_normal_, constant_, xavier_normal_, xavier_uniform_
|
| 13 |
+
|
| 14 |
+
from transformers.integrations import is_deepspeed_zero3_enabled
|
| 15 |
+
|
| 16 |
+
def get_2d_sincos_pos_embed(embed_dim, image_size):
|
| 17 |
+
"""
|
| 18 |
+
image_size: image_size or (image_height, image_width)
|
| 19 |
+
return:
|
| 20 |
+
pos_embed: [image_height, image_width, embed_dim]
|
| 21 |
+
"""
|
| 22 |
+
if isinstance(image_size, int):
|
| 23 |
+
grid_h_size, grid_w_size = image_size, image_size
|
| 24 |
+
else:
|
| 25 |
+
grid_h_size, grid_w_size = image_size[0], image_size[1]
|
| 26 |
+
|
| 27 |
+
grid_h = np.arange(grid_h_size, dtype=np.float32)
|
| 28 |
+
grid_w = np.arange(grid_w_size, dtype=np.float32)
|
| 29 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 30 |
+
grid = np.stack(grid, axis=0)
|
| 31 |
+
|
| 32 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 33 |
+
return pos_embed
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 37 |
+
assert embed_dim % 2 == 0
|
| 38 |
+
|
| 39 |
+
# use half of dimensions to encode grid_h
|
| 40 |
+
emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
|
| 41 |
+
emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
|
| 42 |
+
|
| 43 |
+
emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
|
| 44 |
+
return emb
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
|
| 48 |
+
"""
|
| 49 |
+
embed_dim: output dimension for each position
|
| 50 |
+
pos: a list of positions to be encoded: size (H, W)
|
| 51 |
+
out: (H, W, D)
|
| 52 |
+
"""
|
| 53 |
+
assert embed_dim % 2 == 0
|
| 54 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
| 55 |
+
omega /= embed_dim / 2.
|
| 56 |
+
omega = 1. / 10000 ** omega # (D/2,)
|
| 57 |
+
|
| 58 |
+
out = np.einsum('hw,d->hwd', pos, omega) # (H, W, D/2), outer product
|
| 59 |
+
|
| 60 |
+
emb_sin = np.sin(out) # (H, W, D/2)
|
| 61 |
+
emb_cos = np.cos(out) # (H, W, D/2)
|
| 62 |
+
|
| 63 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
|
| 64 |
+
return emb
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class Resampler(nn.Module):
|
| 68 |
+
"""
|
| 69 |
+
A 2D perceiver-resampler network with one cross attention layers by
|
| 70 |
+
given learnable queries and 2d sincos pos_emb
|
| 71 |
+
Outputs:
|
| 72 |
+
A tensor with the shape of (batch_size, num_queries, embed_dim)
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
num_queries,
|
| 78 |
+
embed_dim,
|
| 79 |
+
num_heads,
|
| 80 |
+
kv_dim=None,
|
| 81 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-6),
|
| 82 |
+
adaptive=False,
|
| 83 |
+
max_size=(70, 70),
|
| 84 |
+
):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.num_queries = num_queries
|
| 87 |
+
self.embed_dim = embed_dim
|
| 88 |
+
self.num_heads = num_heads
|
| 89 |
+
self.adaptive = adaptive
|
| 90 |
+
self.max_size = max_size
|
| 91 |
+
|
| 92 |
+
self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
|
| 93 |
+
|
| 94 |
+
if kv_dim is not None and kv_dim != embed_dim:
|
| 95 |
+
self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
|
| 96 |
+
else:
|
| 97 |
+
self.kv_proj = nn.Identity()
|
| 98 |
+
|
| 99 |
+
self.attn = MultiheadAttention(embed_dim, num_heads)
|
| 100 |
+
self.ln_q = norm_layer(embed_dim)
|
| 101 |
+
self.ln_kv = norm_layer(embed_dim)
|
| 102 |
+
|
| 103 |
+
self.ln_post = norm_layer(embed_dim)
|
| 104 |
+
self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
|
| 105 |
+
|
| 106 |
+
self._set_2d_pos_cache(self.max_size)
|
| 107 |
+
|
| 108 |
+
def _set_2d_pos_cache(self, max_size, device='cpu'):
|
| 109 |
+
if is_deepspeed_zero3_enabled():
|
| 110 |
+
device='cuda'
|
| 111 |
+
pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
|
| 112 |
+
self.register_buffer("pos_embed", pos_embed, persistent=False)
|
| 113 |
+
|
| 114 |
+
def _adjust_pos_cache(self, tgt_sizes, device):
|
| 115 |
+
max_h = torch.max(tgt_sizes[:, 0])
|
| 116 |
+
max_w = torch.max(tgt_sizes[:, 1])
|
| 117 |
+
if max_h > self.max_size[0] or max_w > self.max_size[1]:
|
| 118 |
+
self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
|
| 119 |
+
self._set_2d_pos_cache(self.max_size, device)
|
| 120 |
+
|
| 121 |
+
def _init_weights(self, m):
|
| 122 |
+
if isinstance(m, nn.Linear):
|
| 123 |
+
trunc_normal_(m.weight, std=.02)
|
| 124 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 125 |
+
nn.init.constant_(m.bias, 0)
|
| 126 |
+
elif isinstance(m, nn.LayerNorm):
|
| 127 |
+
nn.init.constant_(m.bias, 0)
|
| 128 |
+
nn.init.constant_(m.weight, 1.0)
|
| 129 |
+
|
| 130 |
+
def forward(self, x, tgt_sizes=None):
|
| 131 |
+
assert x.shape[0] == tgt_sizes.shape[0]
|
| 132 |
+
bs = x.shape[0]
|
| 133 |
+
|
| 134 |
+
device = x.device
|
| 135 |
+
dtype = x.dtype
|
| 136 |
+
|
| 137 |
+
patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
|
| 138 |
+
|
| 139 |
+
self._adjust_pos_cache(tgt_sizes, device=device)
|
| 140 |
+
|
| 141 |
+
max_patch_len = torch.max(patch_len)
|
| 142 |
+
key_padding_mask = torch.zeros((bs, max_patch_len), dtype=torch.bool, device=device)
|
| 143 |
+
|
| 144 |
+
pos_embed = []
|
| 145 |
+
for i in range(bs):
|
| 146 |
+
tgt_h, tgt_w = tgt_sizes[i]
|
| 147 |
+
pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
|
| 148 |
+
key_padding_mask[i, patch_len[i]:] = True
|
| 149 |
+
|
| 150 |
+
pos_embed = torch.nn.utils.rnn.pad_sequence(
|
| 151 |
+
pos_embed, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
|
| 152 |
+
|
| 153 |
+
x = self.kv_proj(x) # B * L * D
|
| 154 |
+
x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
|
| 155 |
+
|
| 156 |
+
q = self.ln_q(self.query) # Q * D
|
| 157 |
+
|
| 158 |
+
out = self.attn(
|
| 159 |
+
self._repeat(q, bs), # Q * B * D
|
| 160 |
+
x + pos_embed, # L * B * D + L * B * D
|
| 161 |
+
x,
|
| 162 |
+
key_padding_mask=key_padding_mask)[0]
|
| 163 |
+
# out: Q * B * D
|
| 164 |
+
x = out.permute(1, 0, 2) # B * Q * D
|
| 165 |
+
|
| 166 |
+
x = self.ln_post(x)
|
| 167 |
+
x = x @ self.proj
|
| 168 |
+
return x
|
| 169 |
+
|
| 170 |
+
def _repeat(self, query, N: int):
|
| 171 |
+
return query.unsqueeze(1).repeat(1, N, 1)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class MultiheadAttention(nn.MultiheadAttention):
|
| 175 |
+
def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False,
|
| 176 |
+
add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None):
|
| 177 |
+
super().__init__(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype)
|
| 178 |
+
|
| 179 |
+
# rewrite out_proj layer,with nn.Linear
|
| 180 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, device=device, dtype=dtype)
|
| 181 |
+
|
| 182 |
+
def forward(
|
| 183 |
+
self,
|
| 184 |
+
query: Tensor,
|
| 185 |
+
key: Tensor,
|
| 186 |
+
value: Tensor,
|
| 187 |
+
key_padding_mask: Optional[Tensor] = None,
|
| 188 |
+
need_weights: bool = True,
|
| 189 |
+
attn_mask: Optional[Tensor] = None,
|
| 190 |
+
average_attn_weights: bool = True,
|
| 191 |
+
is_causal : bool = False) -> Tuple[Tensor, Optional[Tensor]]:
|
| 192 |
+
why_not_fast_path = ''
|
| 193 |
+
if ((attn_mask is not None and torch.is_floating_point(attn_mask))
|
| 194 |
+
or (key_padding_mask is not None) and torch.is_floating_point(key_padding_mask)):
|
| 195 |
+
why_not_fast_path = "floating-point masks are not supported for fast path."
|
| 196 |
+
|
| 197 |
+
is_batched = query.dim() == 3
|
| 198 |
+
|
| 199 |
+
key_padding_mask = _canonical_mask(
|
| 200 |
+
mask=key_padding_mask,
|
| 201 |
+
mask_name="key_padding_mask",
|
| 202 |
+
other_type=F._none_or_dtype(attn_mask),
|
| 203 |
+
other_name="attn_mask",
|
| 204 |
+
target_type=query.dtype
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
attn_mask = _canonical_mask(
|
| 208 |
+
mask=attn_mask,
|
| 209 |
+
mask_name="attn_mask",
|
| 210 |
+
other_type=None,
|
| 211 |
+
other_name="",
|
| 212 |
+
target_type=query.dtype,
|
| 213 |
+
check_other=False,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if not is_batched:
|
| 218 |
+
why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
|
| 219 |
+
elif query is not key or key is not value:
|
| 220 |
+
# When lifting this restriction, don't forget to either
|
| 221 |
+
# enforce that the dtypes all match or test cases where
|
| 222 |
+
# they don't!
|
| 223 |
+
why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
|
| 224 |
+
elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
|
| 225 |
+
why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
|
| 226 |
+
elif self.in_proj_weight is None:
|
| 227 |
+
why_not_fast_path = "in_proj_weight was None"
|
| 228 |
+
elif query.dtype != self.in_proj_weight.dtype:
|
| 229 |
+
# this case will fail anyway, but at least they'll get a useful error message.
|
| 230 |
+
why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
|
| 231 |
+
elif self.training:
|
| 232 |
+
why_not_fast_path = "training is enabled"
|
| 233 |
+
elif (self.num_heads % 2) != 0:
|
| 234 |
+
why_not_fast_path = "self.num_heads is not even"
|
| 235 |
+
elif not self.batch_first:
|
| 236 |
+
why_not_fast_path = "batch_first was not True"
|
| 237 |
+
elif self.bias_k is not None:
|
| 238 |
+
why_not_fast_path = "self.bias_k was not None"
|
| 239 |
+
elif self.bias_v is not None:
|
| 240 |
+
why_not_fast_path = "self.bias_v was not None"
|
| 241 |
+
elif self.add_zero_attn:
|
| 242 |
+
why_not_fast_path = "add_zero_attn was enabled"
|
| 243 |
+
elif not self._qkv_same_embed_dim:
|
| 244 |
+
why_not_fast_path = "_qkv_same_embed_dim was not True"
|
| 245 |
+
elif query.is_nested and (key_padding_mask is not None or attn_mask is not None):
|
| 246 |
+
why_not_fast_path = "supplying both src_key_padding_mask and src_mask at the same time \
|
| 247 |
+
is not supported with NestedTensor input"
|
| 248 |
+
elif torch.is_autocast_enabled():
|
| 249 |
+
why_not_fast_path = "autocast is enabled"
|
| 250 |
+
|
| 251 |
+
if not why_not_fast_path:
|
| 252 |
+
tensor_args = (
|
| 253 |
+
query,
|
| 254 |
+
key,
|
| 255 |
+
value,
|
| 256 |
+
self.in_proj_weight,
|
| 257 |
+
self.in_proj_bias,
|
| 258 |
+
self.out_proj.weight,
|
| 259 |
+
self.out_proj.bias,
|
| 260 |
+
)
|
| 261 |
+
# We have to use list comprehensions below because TorchScript does not support
|
| 262 |
+
# generator expressions.
|
| 263 |
+
if torch.overrides.has_torch_function(tensor_args):
|
| 264 |
+
why_not_fast_path = "some Tensor argument has_torch_function"
|
| 265 |
+
elif _is_make_fx_tracing():
|
| 266 |
+
why_not_fast_path = "we are running make_fx tracing"
|
| 267 |
+
elif not all(_check_arg_device(x) for x in tensor_args):
|
| 268 |
+
why_not_fast_path = ("some Tensor argument's device is neither one of "
|
| 269 |
+
f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}")
|
| 270 |
+
elif torch.is_grad_enabled() and any(_arg_requires_grad(x) for x in tensor_args):
|
| 271 |
+
why_not_fast_path = ("grad is enabled and at least one of query or the "
|
| 272 |
+
"input/output projection weights or biases requires_grad")
|
| 273 |
+
if not why_not_fast_path:
|
| 274 |
+
merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
|
| 275 |
+
|
| 276 |
+
if self.in_proj_bias is not None and self.in_proj_weight is not None:
|
| 277 |
+
return torch._native_multi_head_attention(
|
| 278 |
+
query,
|
| 279 |
+
key,
|
| 280 |
+
value,
|
| 281 |
+
self.embed_dim,
|
| 282 |
+
self.num_heads,
|
| 283 |
+
self.in_proj_weight,
|
| 284 |
+
self.in_proj_bias,
|
| 285 |
+
self.out_proj.weight,
|
| 286 |
+
self.out_proj.bias,
|
| 287 |
+
merged_mask,
|
| 288 |
+
need_weights,
|
| 289 |
+
average_attn_weights,
|
| 290 |
+
mask_type)
|
| 291 |
+
|
| 292 |
+
any_nested = query.is_nested or key.is_nested or value.is_nested
|
| 293 |
+
assert not any_nested, ("MultiheadAttention does not support NestedTensor outside of its fast path. " +
|
| 294 |
+
f"The fast path was not hit because {why_not_fast_path}")
|
| 295 |
+
|
| 296 |
+
if self.batch_first and is_batched:
|
| 297 |
+
# make sure that the transpose op does not affect the "is" property
|
| 298 |
+
if key is value:
|
| 299 |
+
if query is key:
|
| 300 |
+
query = key = value = query.transpose(1, 0)
|
| 301 |
+
else:
|
| 302 |
+
query, key = (x.transpose(1, 0) for x in (query, key))
|
| 303 |
+
value = key
|
| 304 |
+
else:
|
| 305 |
+
query, key, value = (x.transpose(1, 0) for x in (query, key, value))
|
| 306 |
+
|
| 307 |
+
if not self._qkv_same_embed_dim:
|
| 308 |
+
attn_output, attn_output_weights = self.multi_head_attention_forward(
|
| 309 |
+
query, key, value, self.embed_dim, self.num_heads,
|
| 310 |
+
self.in_proj_weight, self.in_proj_bias,
|
| 311 |
+
self.bias_k, self.bias_v, self.add_zero_attn,
|
| 312 |
+
self.dropout, self.out_proj.weight, self.out_proj.bias,
|
| 313 |
+
training=self.training,
|
| 314 |
+
key_padding_mask=key_padding_mask, need_weights=need_weights,
|
| 315 |
+
attn_mask=attn_mask,
|
| 316 |
+
use_separate_proj_weight=True,
|
| 317 |
+
q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
|
| 318 |
+
v_proj_weight=self.v_proj_weight,
|
| 319 |
+
average_attn_weights=average_attn_weights,
|
| 320 |
+
is_causal=is_causal)
|
| 321 |
+
else:
|
| 322 |
+
attn_output, attn_output_weights = self.multi_head_attention_forward(
|
| 323 |
+
query, key, value, self.embed_dim, self.num_heads,
|
| 324 |
+
self.in_proj_weight, self.in_proj_bias,
|
| 325 |
+
self.bias_k, self.bias_v, self.add_zero_attn,
|
| 326 |
+
self.dropout, self.out_proj.weight, self.out_proj.bias,
|
| 327 |
+
training=self.training,
|
| 328 |
+
key_padding_mask=key_padding_mask,
|
| 329 |
+
need_weights=need_weights,
|
| 330 |
+
attn_mask=attn_mask,
|
| 331 |
+
average_attn_weights=average_attn_weights,
|
| 332 |
+
is_causal=is_causal)
|
| 333 |
+
if self.batch_first and is_batched:
|
| 334 |
+
return attn_output.transpose(1, 0), attn_output_weights
|
| 335 |
+
else:
|
| 336 |
+
return attn_output, attn_output_weights
|
| 337 |
+
|
| 338 |
+
def multi_head_attention_forward(
|
| 339 |
+
self,
|
| 340 |
+
query: Tensor,
|
| 341 |
+
key: Tensor,
|
| 342 |
+
value: Tensor,
|
| 343 |
+
embed_dim_to_check: int,
|
| 344 |
+
num_heads: int,
|
| 345 |
+
in_proj_weight: Optional[Tensor],
|
| 346 |
+
in_proj_bias: Optional[Tensor],
|
| 347 |
+
bias_k: Optional[Tensor],
|
| 348 |
+
bias_v: Optional[Tensor],
|
| 349 |
+
add_zero_attn: bool,
|
| 350 |
+
dropout_p: float,
|
| 351 |
+
out_proj_weight: Tensor,
|
| 352 |
+
out_proj_bias: Optional[Tensor],
|
| 353 |
+
training: bool = True,
|
| 354 |
+
key_padding_mask: Optional[Tensor] = None,
|
| 355 |
+
need_weights: bool = True,
|
| 356 |
+
attn_mask: Optional[Tensor] = None,
|
| 357 |
+
use_separate_proj_weight: bool = False,
|
| 358 |
+
q_proj_weight: Optional[Tensor] = None,
|
| 359 |
+
k_proj_weight: Optional[Tensor] = None,
|
| 360 |
+
v_proj_weight: Optional[Tensor] = None,
|
| 361 |
+
static_k: Optional[Tensor] = None,
|
| 362 |
+
static_v: Optional[Tensor] = None,
|
| 363 |
+
average_attn_weights: bool = True,
|
| 364 |
+
is_causal: bool = False,
|
| 365 |
+
) -> Tuple[Tensor, Optional[Tensor]]:
|
| 366 |
+
tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
|
| 367 |
+
|
| 368 |
+
is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
|
| 369 |
+
|
| 370 |
+
# For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
|
| 371 |
+
# is batched, run the computation and before returning squeeze the
|
| 372 |
+
# batch dimension so that the output doesn't carry this temporary batch dimension.
|
| 373 |
+
if not is_batched:
|
| 374 |
+
# unsqueeze if the input is unbatched
|
| 375 |
+
query = query.unsqueeze(1)
|
| 376 |
+
key = key.unsqueeze(1)
|
| 377 |
+
value = value.unsqueeze(1)
|
| 378 |
+
if key_padding_mask is not None:
|
| 379 |
+
key_padding_mask = key_padding_mask.unsqueeze(0)
|
| 380 |
+
|
| 381 |
+
# set up shape vars
|
| 382 |
+
tgt_len, bsz, embed_dim = query.shape
|
| 383 |
+
src_len, _, _ = key.shape
|
| 384 |
+
|
| 385 |
+
key_padding_mask = _canonical_mask(
|
| 386 |
+
mask=key_padding_mask,
|
| 387 |
+
mask_name="key_padding_mask",
|
| 388 |
+
other_type=_none_or_dtype(attn_mask),
|
| 389 |
+
other_name="attn_mask",
|
| 390 |
+
target_type=query.dtype
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
if is_causal and attn_mask is None:
|
| 394 |
+
raise RuntimeError(
|
| 395 |
+
"Need attn_mask if specifying the is_causal hint. "
|
| 396 |
+
"You may use the Transformer module method "
|
| 397 |
+
"`generate_square_subsequent_mask` to create this mask."
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
if is_causal and key_padding_mask is None and not need_weights:
|
| 401 |
+
# when we have a kpm or need weights, we need attn_mask
|
| 402 |
+
# Otherwise, we use the is_causal hint go as is_causal
|
| 403 |
+
# indicator to SDPA.
|
| 404 |
+
attn_mask = None
|
| 405 |
+
else:
|
| 406 |
+
attn_mask = _canonical_mask(
|
| 407 |
+
mask=attn_mask,
|
| 408 |
+
mask_name="attn_mask",
|
| 409 |
+
other_type=None,
|
| 410 |
+
other_name="",
|
| 411 |
+
target_type=query.dtype,
|
| 412 |
+
check_other=False,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
if key_padding_mask is not None:
|
| 416 |
+
# We have the attn_mask, and use that to merge kpm into it.
|
| 417 |
+
# Turn off use of is_causal hint, as the merged mask is no
|
| 418 |
+
# longer causal.
|
| 419 |
+
is_causal = False
|
| 420 |
+
|
| 421 |
+
assert embed_dim == embed_dim_to_check, \
|
| 422 |
+
f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
|
| 423 |
+
if isinstance(embed_dim, torch.Tensor):
|
| 424 |
+
# embed_dim can be a tensor when JIT tracing
|
| 425 |
+
head_dim = embed_dim.div(num_heads, rounding_mode='trunc')
|
| 426 |
+
else:
|
| 427 |
+
head_dim = embed_dim // num_heads
|
| 428 |
+
assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
|
| 429 |
+
if use_separate_proj_weight:
|
| 430 |
+
# allow MHA to have different embedding dimensions when separate projection weights are used
|
| 431 |
+
assert key.shape[:2] == value.shape[:2], \
|
| 432 |
+
f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
|
| 433 |
+
else:
|
| 434 |
+
assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
|
| 435 |
+
|
| 436 |
+
#
|
| 437 |
+
# compute in-projection
|
| 438 |
+
#
|
| 439 |
+
if not use_separate_proj_weight:
|
| 440 |
+
assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
|
| 441 |
+
q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
|
| 442 |
+
else:
|
| 443 |
+
assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
|
| 444 |
+
assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
|
| 445 |
+
assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
|
| 446 |
+
if in_proj_bias is None:
|
| 447 |
+
b_q = b_k = b_v = None
|
| 448 |
+
else:
|
| 449 |
+
b_q, b_k, b_v = in_proj_bias.chunk(3)
|
| 450 |
+
q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
|
| 451 |
+
|
| 452 |
+
# prep attention mask
|
| 453 |
+
|
| 454 |
+
if attn_mask is not None:
|
| 455 |
+
# ensure attn_mask's dim is 3
|
| 456 |
+
if attn_mask.dim() == 2:
|
| 457 |
+
correct_2d_size = (tgt_len, src_len)
|
| 458 |
+
if attn_mask.shape != correct_2d_size:
|
| 459 |
+
raise RuntimeError(f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.")
|
| 460 |
+
attn_mask = attn_mask.unsqueeze(0)
|
| 461 |
+
elif attn_mask.dim() == 3:
|
| 462 |
+
correct_3d_size = (bsz * num_heads, tgt_len, src_len)
|
| 463 |
+
if attn_mask.shape != correct_3d_size:
|
| 464 |
+
raise RuntimeError(f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.")
|
| 465 |
+
else:
|
| 466 |
+
raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
|
| 467 |
+
|
| 468 |
+
# add bias along batch dimension (currently second)
|
| 469 |
+
if bias_k is not None and bias_v is not None:
|
| 470 |
+
assert static_k is None, "bias cannot be added to static key."
|
| 471 |
+
assert static_v is None, "bias cannot be added to static value."
|
| 472 |
+
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
| 473 |
+
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
| 474 |
+
if attn_mask is not None:
|
| 475 |
+
attn_mask = pad(attn_mask, (0, 1))
|
| 476 |
+
if key_padding_mask is not None:
|
| 477 |
+
key_padding_mask = pad(key_padding_mask, (0, 1))
|
| 478 |
+
else:
|
| 479 |
+
assert bias_k is None
|
| 480 |
+
assert bias_v is None
|
| 481 |
+
|
| 482 |
+
#
|
| 483 |
+
# reshape q, k, v for multihead attention and make em batch first
|
| 484 |
+
#
|
| 485 |
+
q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
|
| 486 |
+
if static_k is None:
|
| 487 |
+
k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
| 488 |
+
else:
|
| 489 |
+
# TODO finish disentangling control flow so we don't do in-projections when statics are passed
|
| 490 |
+
assert static_k.size(0) == bsz * num_heads, \
|
| 491 |
+
f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
|
| 492 |
+
assert static_k.size(2) == head_dim, \
|
| 493 |
+
f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
|
| 494 |
+
k = static_k
|
| 495 |
+
if static_v is None:
|
| 496 |
+
v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
| 497 |
+
else:
|
| 498 |
+
# TODO finish disentangling control flow so we don't do in-projections when statics are passed
|
| 499 |
+
assert static_v.size(0) == bsz * num_heads, \
|
| 500 |
+
f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
|
| 501 |
+
assert static_v.size(2) == head_dim, \
|
| 502 |
+
f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
|
| 503 |
+
v = static_v
|
| 504 |
+
|
| 505 |
+
# add zero attention along batch dimension (now first)
|
| 506 |
+
if add_zero_attn:
|
| 507 |
+
zero_attn_shape = (bsz * num_heads, 1, head_dim)
|
| 508 |
+
k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
|
| 509 |
+
v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
|
| 510 |
+
if attn_mask is not None:
|
| 511 |
+
attn_mask = pad(attn_mask, (0, 1))
|
| 512 |
+
if key_padding_mask is not None:
|
| 513 |
+
key_padding_mask = pad(key_padding_mask, (0, 1))
|
| 514 |
+
|
| 515 |
+
# update source sequence length after adjustments
|
| 516 |
+
src_len = k.size(1)
|
| 517 |
+
|
| 518 |
+
# merge key padding and attention masks
|
| 519 |
+
if key_padding_mask is not None:
|
| 520 |
+
assert key_padding_mask.shape == (bsz, src_len), \
|
| 521 |
+
f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
|
| 522 |
+
key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len). \
|
| 523 |
+
expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
|
| 524 |
+
if attn_mask is None:
|
| 525 |
+
attn_mask = key_padding_mask
|
| 526 |
+
else:
|
| 527 |
+
attn_mask = attn_mask + key_padding_mask
|
| 528 |
+
|
| 529 |
+
# adjust dropout probability
|
| 530 |
+
if not training:
|
| 531 |
+
dropout_p = 0.0
|
| 532 |
+
|
| 533 |
+
#
|
| 534 |
+
# (deep breath) calculate attention and out projection
|
| 535 |
+
#
|
| 536 |
+
|
| 537 |
+
if need_weights:
|
| 538 |
+
B, Nt, E = q.shape
|
| 539 |
+
q_scaled = q / math.sqrt(E)
|
| 540 |
+
|
| 541 |
+
assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
|
| 542 |
+
|
| 543 |
+
if attn_mask is not None:
|
| 544 |
+
attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
|
| 545 |
+
else:
|
| 546 |
+
attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
|
| 547 |
+
attn_output_weights = softmax(attn_output_weights, dim=-1)
|
| 548 |
+
if dropout_p > 0.0:
|
| 549 |
+
attn_output_weights = dropout(attn_output_weights, p=dropout_p)
|
| 550 |
+
|
| 551 |
+
attn_output = torch.bmm(attn_output_weights, v)
|
| 552 |
+
|
| 553 |
+
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
|
| 554 |
+
attn_output = self.out_proj(attn_output)
|
| 555 |
+
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
| 556 |
+
|
| 557 |
+
# optionally average attention weights over heads
|
| 558 |
+
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
|
| 559 |
+
if average_attn_weights:
|
| 560 |
+
attn_output_weights = attn_output_weights.mean(dim=1)
|
| 561 |
+
|
| 562 |
+
if not is_batched:
|
| 563 |
+
# squeeze the output if input was unbatched
|
| 564 |
+
attn_output = attn_output.squeeze(1)
|
| 565 |
+
attn_output_weights = attn_output_weights.squeeze(0)
|
| 566 |
+
return attn_output, attn_output_weights
|
| 567 |
+
else:
|
| 568 |
+
# attn_mask can be either (L,S) or (N*num_heads, L, S)
|
| 569 |
+
# if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
|
| 570 |
+
# in order to match the input for SDPA of (N, num_heads, L, S)
|
| 571 |
+
if attn_mask is not None:
|
| 572 |
+
if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
|
| 573 |
+
attn_mask = attn_mask.unsqueeze(0)
|
| 574 |
+
else:
|
| 575 |
+
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
|
| 576 |
+
|
| 577 |
+
q = q.view(bsz, num_heads, tgt_len, head_dim)
|
| 578 |
+
k = k.view(bsz, num_heads, src_len, head_dim)
|
| 579 |
+
v = v.view(bsz, num_heads, src_len, head_dim)
|
| 580 |
+
|
| 581 |
+
attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
|
| 582 |
+
attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
|
| 583 |
+
|
| 584 |
+
attn_output = self.out_proj(attn_output)
|
| 585 |
+
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
| 586 |
+
if not is_batched:
|
| 587 |
+
# squeeze the output if input was unbatched
|
| 588 |
+
attn_output = attn_output.squeeze(1)
|
| 589 |
+
return attn_output, None
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def _mha_shape_check(query: Tensor, key: Tensor, value: Tensor,
|
| 593 |
+
key_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor], num_heads: int):
|
| 594 |
+
# Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
|
| 595 |
+
# and returns if the input is batched or not.
|
| 596 |
+
# Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
|
| 597 |
+
|
| 598 |
+
# Shape check.
|
| 599 |
+
if query.dim() == 3:
|
| 600 |
+
# Batched Inputs
|
| 601 |
+
is_batched = True
|
| 602 |
+
assert key.dim() == 3 and value.dim() == 3, \
|
| 603 |
+
("For batched (3-D) `query`, expected `key` and `value` to be 3-D"
|
| 604 |
+
f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
|
| 605 |
+
if key_padding_mask is not None:
|
| 606 |
+
assert key_padding_mask.dim() == 2, \
|
| 607 |
+
("For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
|
| 608 |
+
f" but found {key_padding_mask.dim()}-D tensor instead")
|
| 609 |
+
if attn_mask is not None:
|
| 610 |
+
assert attn_mask.dim() in (2, 3), \
|
| 611 |
+
("For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
|
| 612 |
+
f" but found {attn_mask.dim()}-D tensor instead")
|
| 613 |
+
elif query.dim() == 2:
|
| 614 |
+
# Unbatched Inputs
|
| 615 |
+
is_batched = False
|
| 616 |
+
assert key.dim() == 2 and value.dim() == 2, \
|
| 617 |
+
("For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
|
| 618 |
+
f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
|
| 619 |
+
|
| 620 |
+
if key_padding_mask is not None:
|
| 621 |
+
assert key_padding_mask.dim() == 1, \
|
| 622 |
+
("For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
|
| 623 |
+
f" but found {key_padding_mask.dim()}-D tensor instead")
|
| 624 |
+
|
| 625 |
+
if attn_mask is not None:
|
| 626 |
+
assert attn_mask.dim() in (2, 3), \
|
| 627 |
+
("For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
|
| 628 |
+
f" but found {attn_mask.dim()}-D tensor instead")
|
| 629 |
+
if attn_mask.dim() == 3:
|
| 630 |
+
expected_shape = (num_heads, query.shape[0], key.shape[0])
|
| 631 |
+
assert attn_mask.shape == expected_shape, \
|
| 632 |
+
(f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}")
|
| 633 |
+
else:
|
| 634 |
+
raise AssertionError(
|
| 635 |
+
f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor")
|
| 636 |
+
|
| 637 |
+
return is_batched
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def _canonical_mask(
|
| 641 |
+
mask: Optional[Tensor],
|
| 642 |
+
mask_name: str,
|
| 643 |
+
other_type: Optional[DType],
|
| 644 |
+
other_name: str,
|
| 645 |
+
target_type: DType,
|
| 646 |
+
check_other: bool = True,
|
| 647 |
+
) -> Optional[Tensor]:
|
| 648 |
+
|
| 649 |
+
if mask is not None:
|
| 650 |
+
_mask_dtype = mask.dtype
|
| 651 |
+
_mask_is_float = torch.is_floating_point(mask)
|
| 652 |
+
if _mask_dtype != torch.bool and not _mask_is_float:
|
| 653 |
+
raise AssertionError(
|
| 654 |
+
f"only bool and floating types of {mask_name} are supported")
|
| 655 |
+
if check_other and other_type is not None:
|
| 656 |
+
if _mask_dtype != other_type:
|
| 657 |
+
warnings.warn(
|
| 658 |
+
f"Support for mismatched {mask_name} and {other_name} "
|
| 659 |
+
"is deprecated. Use same type for both instead."
|
| 660 |
+
)
|
| 661 |
+
if not _mask_is_float:
|
| 662 |
+
mask = (
|
| 663 |
+
torch.zeros_like(mask, dtype=target_type)
|
| 664 |
+
.masked_fill_(mask, float("-inf"))
|
| 665 |
+
)
|
| 666 |
+
return mask
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
|
| 670 |
+
if input is None:
|
| 671 |
+
return None
|
| 672 |
+
elif isinstance(input, torch.Tensor):
|
| 673 |
+
return input.dtype
|
| 674 |
+
raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
|
| 675 |
+
|
| 676 |
+
def _in_projection_packed(
|
| 677 |
+
q: Tensor,
|
| 678 |
+
k: Tensor,
|
| 679 |
+
v: Tensor,
|
| 680 |
+
w: Tensor,
|
| 681 |
+
b: Optional[Tensor] = None,
|
| 682 |
+
) -> List[Tensor]:
|
| 683 |
+
r"""
|
| 684 |
+
Performs the in-projection step of the attention operation, using packed weights.
|
| 685 |
+
Output is a triple containing projection tensors for query, key and value.
|
| 686 |
+
Args:
|
| 687 |
+
q, k, v: query, key and value tensors to be projected. For self-attention,
|
| 688 |
+
these are typically the same tensor; for encoder-decoder attention,
|
| 689 |
+
k and v are typically the same tensor. (We take advantage of these
|
| 690 |
+
identities for performance if they are present.) Regardless, q, k and v
|
| 691 |
+
must share a common embedding dimension; otherwise their shapes may vary.
|
| 692 |
+
w: projection weights for q, k and v, packed into a single tensor. Weights
|
| 693 |
+
are packed along dimension 0, in q, k, v order.
|
| 694 |
+
b: optional projection biases for q, k and v, packed into a single tensor
|
| 695 |
+
in q, k, v order.
|
| 696 |
+
Shape:
|
| 697 |
+
Inputs:
|
| 698 |
+
- q: :math:`(..., E)` where E is the embedding dimension
|
| 699 |
+
- k: :math:`(..., E)` where E is the embedding dimension
|
| 700 |
+
- v: :math:`(..., E)` where E is the embedding dimension
|
| 701 |
+
- w: :math:`(E * 3, E)` where E is the embedding dimension
|
| 702 |
+
- b: :math:`E * 3` where E is the embedding dimension
|
| 703 |
+
Output:
|
| 704 |
+
- in output list :math:`[q', k', v']`, each output tensor will have the
|
| 705 |
+
same shape as the corresponding input tensor.
|
| 706 |
+
"""
|
| 707 |
+
E = q.size(-1)
|
| 708 |
+
if k is v:
|
| 709 |
+
if q is k:
|
| 710 |
+
# self-attention
|
| 711 |
+
proj = linear(q, w, b)
|
| 712 |
+
# reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
|
| 713 |
+
proj = proj.unflatten(-1, (3, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
|
| 714 |
+
return proj[0], proj[1], proj[2]
|
| 715 |
+
else:
|
| 716 |
+
# encoder-decoder attention
|
| 717 |
+
w_q, w_kv = w.split([E, E * 2])
|
| 718 |
+
if b is None:
|
| 719 |
+
b_q = b_kv = None
|
| 720 |
+
else:
|
| 721 |
+
b_q, b_kv = b.split([E, E * 2])
|
| 722 |
+
q_proj = linear(q, w_q, b_q)
|
| 723 |
+
kv_proj = linear(k, w_kv, b_kv)
|
| 724 |
+
# reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
|
| 725 |
+
kv_proj = kv_proj.unflatten(-1, (2, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
|
| 726 |
+
return (q_proj, kv_proj[0], kv_proj[1])
|
| 727 |
+
else:
|
| 728 |
+
w_q, w_k, w_v = w.chunk(3)
|
| 729 |
+
if b is None:
|
| 730 |
+
b_q = b_k = b_v = None
|
| 731 |
+
else:
|
| 732 |
+
b_q, b_k, b_v = b.chunk(3)
|
| 733 |
+
return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def _in_projection(
|
| 737 |
+
q: Tensor,
|
| 738 |
+
k: Tensor,
|
| 739 |
+
v: Tensor,
|
| 740 |
+
w_q: Tensor,
|
| 741 |
+
w_k: Tensor,
|
| 742 |
+
w_v: Tensor,
|
| 743 |
+
b_q: Optional[Tensor] = None,
|
| 744 |
+
b_k: Optional[Tensor] = None,
|
| 745 |
+
b_v: Optional[Tensor] = None,
|
| 746 |
+
) -> Tuple[Tensor, Tensor, Tensor]:
|
| 747 |
+
r"""
|
| 748 |
+
Performs the in-projection step of the attention operation. This is simply
|
| 749 |
+
a triple of linear projections, with shape constraints on the weights which
|
| 750 |
+
ensure embedding dimension uniformity in the projected outputs.
|
| 751 |
+
Output is a triple containing projection tensors for query, key and value.
|
| 752 |
+
Args:
|
| 753 |
+
q, k, v: query, key and value tensors to be projected.
|
| 754 |
+
w_q, w_k, w_v: weights for q, k and v, respectively.
|
| 755 |
+
b_q, b_k, b_v: optional biases for q, k and v, respectively.
|
| 756 |
+
Shape:
|
| 757 |
+
Inputs:
|
| 758 |
+
- q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
|
| 759 |
+
number of leading dimensions.
|
| 760 |
+
- k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
|
| 761 |
+
number of leading dimensions.
|
| 762 |
+
- v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
|
| 763 |
+
number of leading dimensions.
|
| 764 |
+
- w_q: :math:`(Eq, Eq)`
|
| 765 |
+
- w_k: :math:`(Eq, Ek)`
|
| 766 |
+
- w_v: :math:`(Eq, Ev)`
|
| 767 |
+
- b_q: :math:`(Eq)`
|
| 768 |
+
- b_k: :math:`(Eq)`
|
| 769 |
+
- b_v: :math:`(Eq)`
|
| 770 |
+
Output: in output triple :math:`(q', k', v')`,
|
| 771 |
+
- q': :math:`[Qdims..., Eq]`
|
| 772 |
+
- k': :math:`[Kdims..., Eq]`
|
| 773 |
+
- v': :math:`[Vdims..., Eq]`
|
| 774 |
+
"""
|
| 775 |
+
Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
|
| 776 |
+
assert w_q.shape == (Eq, Eq), f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
|
| 777 |
+
assert w_k.shape == (Eq, Ek), f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
|
| 778 |
+
assert w_v.shape == (Eq, Ev), f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
|
| 779 |
+
assert b_q is None or b_q.shape == (Eq,), f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
|
| 780 |
+
assert b_k is None or b_k.shape == (Eq,), f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
|
| 781 |
+
assert b_v is None or b_v.shape == (Eq,), f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
|
| 782 |
+
return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
|