File size: 27,303 Bytes
72edb83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
---
language:
- en
tags:
- facebook
- meta
- pytorch
- plm
- arxiv:2504.13180
extra_gated_prompt: >+
  FAIR Noncommercial Research License

  Last Updated: April 17, 2025


  “Acceptable Use Policy” means the FAIR Acceptable Use Policy, applicable to
  Research Materials, that is incorporated into this Agreement.


  “Agreement” means the terms and conditions for use, reproduction, distribution
  and modification of the Research Materials set forth herein.



  “Documentation” means the specifications, manuals and documentation
  accompanying 

  Research Materials distributed by Meta.



  “Licensee” or “you” means you, or your employer or any other person or entity
  (if you are entering into this Agreement on such person or entity’s behalf),
  of the age required under applicable laws, rules or regulations to provide
  legal consent and that has legal authority to bind your employer or such other
  person or entity if you are entering in this Agreement on their behalf.



  “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or,
  if you are an entity, your principal place of business is in the EEA or
  Switzerland) and Meta Platforms, Inc. (if you are located outside of the EEA
  or Switzerland).


  “Noncommercial Research Uses” means noncommercial research use cases related
  to research, development, education, processing, or analysis and in each case,
  is not primarily intended for commercial advantage or monetary compensation to
  you or others.


  “Research Materials” means, collectively, Documentation and the models,
  software and algorithms, including machine-learning model code, trained model
  weights, inference-enabling code, training-enabling code, fine-tuning enabling
  code, demonstration materials and other elements of the foregoing distributed
  by Meta and made available under this Agreement.


  By clicking “I Accept” below or by using or distributing any portion or
  element of the Research Materials, you agree to be bound by this Agreement.



  1. License Rights and Redistribution.



  a. Grant of Rights. You are granted a non-exclusive, worldwide,
  non-transferable and royalty-free limited license under Meta’s intellectual
  property or other rights owned by Meta embodied in the Research Materials to
  use, reproduce, distribute, copy, create derivative works of, and make
  modifications to the Research Materials.  
   
  b. Redistribution and Use.  
   i. You will not use the Research Materials or any outputs or results of the Research Materials in connection with any commercial uses or for any uses other than Noncommercial Research Uses;


  ii. Distribution of Research Materials, and any derivative works thereof, are
  subject to the terms of this Agreement. If you distribute or make the Research
  Materials, or any derivative works thereof, available to a third party, you
  may only do so under the terms of this Agreement. You shall also provide a
  copy of this Agreement to such third party.



  iii.  If you submit for publication the results of research you perform on,
  using, or otherwise in connection with Research Materials, you must
  acknowledge the use of Research Materials in your publication.



  iv. Your use of the Research Materials must comply with applicable laws and
  regulations (including Trade Control Laws) and adhere to the FAIR Acceptable
  Use Policy, which is hereby incorporated by reference into this Agreement.

  2. User Support. Your Noncommercial Research Use of the Research Materials is
  done at your own discretion; Meta does not process any information nor provide
  any service in relation to such use.  Meta is under no obligation to provide
  any support services for the Research Materials. Any support provided is “as
  is”, “with all faults”, and without warranty of any kind.



  3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE RESEARCH
  MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS”
  BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF
  ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY
  WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A
  PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE
  APPROPRIATENESS OF USING OR REDISTRIBUTING THE RESEARCH MATERIALS AND ASSUME
  ANY RISKS ASSOCIATED WITH YOUR USE OF THE RESEARCH MATERIALS AND ANY OUTPUT
  AND RESULTS.
   
  4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE
  UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS
  LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS
  OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR
  PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE
  POSSIBILITY OF ANY OF THE FOREGOING.
   
  5. Intellectual Property.



  a. Subject to Meta’s ownership of Research Materials and derivatives made by
  or for Meta, with respect to any derivative works and modifications of the
  Research Materials that are made by you, as between you and Meta, you are and
  will be the owner of such derivative works and modifications.
   
  b. If you institute litigation or other proceedings against Meta or any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that the
  Research Materials, outputs or results, or any portion of any of the
  foregoing, constitutes infringement of intellectual property or other rights
  owned or licensable by you, then any licenses granted to you under this
  Agreement shall terminate as of the date such litigation or claim is filed or
  instituted. You will indemnify and hold harmless Meta from and against any
  claim by any third party arising out of or related to your use or distribution
  of the Research Materials.
   
  6. Term and Termination. The term of this Agreement will commence upon your
  acceptance of this Agreement or access to the Research Materials and will
  continue in full force and effect until terminated in accordance with the
  terms and conditions herein. Meta may terminate this Agreement if you are in
  breach of any term or condition of this Agreement. Upon termination of this
  Agreement, you shall delete and cease use of the Research Materials. Sections
  5, 6 and 9 shall survive the termination of this Agreement. 
   
  7. Governing Law and Jurisdiction. This Agreement will be governed and
  construed under the laws of the State of California without regard to choice
  of law principles, and the UN Convention on Contracts for the International
  Sale of Goods does not apply to this Agreement. The courts of California shall
  have exclusive jurisdiction of any dispute arising out of this Agreement. 



  8. Modifications and Amendments. Meta may modify this Agreement from time to
  time by posting a revised version at
  [https://huggingface.co/facebook/Perception-LM-8B/blob/main/LICENSE]; provided
  that they are similar in spirit to the current version of the Agreement, but
  may differ in detail to address new problems or concerns. All such changes
  will be effective immediately. Your continued use of the Research Materials
  after any modification to this Agreement constitutes your agreement to such
  modification. Except as provided in this Agreement, no modification or
  addition to any provision of this Agreement will be binding unless it is in
  writing and signed by an authorized representative of both you and Meta.



  FAIR Acceptable Use Policy 


  The Fundamental AI Research (FAIR) team at Meta seeks to further understanding
  of new and existing research domains with the mission of advancing the
  state-of-the-art in artificial intelligence through open research for the
  benefit of all. 


  As part of this mission, Meta makes certain research materials available for
  noncommercial research use. Meta is committed to promoting the safe and
  responsible use of such research materials.  


  Prohibited Uses


  You agree you will not use, or allow others to use, Research Materials to:

   Violate the law or others’ rights, including to:
  Engage in, promote, generate, contribute to, encourage, plan, incite, or
  further illegal or unlawful activity or content, such as:

  Violence or terrorism

  Exploitation or harm to children, including the solicitation, creation,
  acquisition, or dissemination of child exploitative content or failure to
  report Child Sexual Abuse Material

  Human trafficking, exploitation, and sexual violence

  The illegal distribution of information or materials to minors, including
  obscene materials, or failure to employ legally required age-gating in
  connection with such information or materials.

  Sexual solicitation

  Any other criminal activity


  Engage in, promote, incite, or facilitate the harassment, abuse, threatening,
  or bullying of individuals or groups of individuals


  Engage in, promote, incite, or facilitate discrimination or other unlawful or
  harmful conduct in the provision of employment, employment benefits, credit,
  housing, other economic benefits, or other essential goods and services


  Engage in the unauthorized or unlicensed practice of any profession including,
  but not limited to, financial, legal, medical/health, or related professional
  practices


  Collect, process, disclose, generate, or infer health, demographic, or other
  sensitive personal or private information about individuals without rights and
  consents required by applicable laws


  Engage in or facilitate any action or generate any content that infringes,
  misappropriates, or otherwise violates any third-party rights, including the
  outputs or results of any technology using FAIR research materials


  Create, generate, or facilitate the creation of malicious code, malware,
  computer viruses or do anything else that could disable, overburden, interfere
  with or impair the proper working, integrity, operation or appearance of a
  website or computer system


  2. Engage in, promote, incite, facilitate, or assist in the planning or
  development of activities that present a risk of death or bodily harm to
  individuals, including use of research artifacts related to the following:


  Military, warfare, nuclear industries or applications, espionage, use for
  materials or activities that are subject to the International Traffic Arms
  Regulations (ITAR) maintained by the United States Department of State


  Guns and illegal weapons (including weapon development)


  Illegal drugs and regulated/controlled substances


  Operation of critical infrastructure, transportation technologies, or heavy
  machinery


  Self-harm or harm to others, including suicide, cutting, and eating disorders


  Any content intended to incite or promote violence, abuse, or any infliction
  of bodily harm to an individual


  3. Intentionally deceive or mislead others, including use of FAIR Research
  Materials related to the following:

   Generating, promoting, or furthering fraud or the creation or promotion of disinformation

   Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content

  Generating, promoting, or further distributing spam

   Impersonating another individual without consent, authorization, or legal right

  Representing that outputs of FAIR research materials or outputs from
  technology using FAIR research materials are human-generated


  Generating or facilitating false online engagement, including fake reviews and
  other means of fake online engagement


  4. Fail to appropriately disclose to end users any known dangers of your
  Research Materials.


  Please report any violation of this Policy or other problems that could lead
  to a violation of this Policy by submitting a report here
  [https://docs.google.com/forms/d/e/1FAIpQLSeb11cryAopJ7LNrC4nxEUXrHY26hfkXQMf_uH-oFgA3WlYZQ/viewform]. 

extra_gated_fields:
  First Name: text
  Last Name: text
  Date of birth: date_picker
  Country: country
  Affiliation: text
  Job title:
    type: select
    options:
    - Student
    - Research Graduate
    - AI researcher
    - AI developer/engineer
    - Reporter
    - Other
  geo: ip_location
  By clicking Submit below I accept the terms of the license and acknowledge that the information I provide will be collected stored processed and shared in accordance with the Meta Privacy Policy: checkbox
extra_gated_description: >-
  The information you provide will be collected, stored, processed and shared in
  accordance with the [Meta Privacy
  Policy](https://www.facebook.com/privacy/policy/).
extra_gated_button_content: Submit
extra_gated_heading: >-
  Please be sure to provide your full legal name, date of birth, and full
  organization name with all corporate identifiers. Avoid the use of acronyms
  and special characters. Failure to follow these instructions may prevent you
  from accessing this model and others on Hugging Face. You will not have the
  ability to edit this form after submission, so please ensure all information
  is accurate.
license: other
license_name: fair-noncommercial-research
pipeline_tag: image-text-to-text
---
# Model Details

Perception Language Model (PLM) is a state-of-the-art, fully open and reproducible MLLM for transparent research in image and video understanding. It was introduced in "[PerceptionLM: Open-Access Data and Models for
Detailed Visual Understanding](https://ai.meta.com/research/publications/perceptionlm-open-access-data-and-models-for-detailed-visual-understanding)".

[\[📃 Tech Report\]](https://arxiv.org/abs/2504.13180)
[\[📂 Github\]](https://github.com/facebookresearch/perception_models/)

**Model Overview**: PLM consists of a vision encoder with a small scale (<8B parameters) LLM decoder. We start by an analysis of standard training pipelines with available data, without any proprietary model distillation. We investigate large-scale
synthetic data and establish key scaling laws to identify critical data gaps that limit video understanding performance, especially for spatio-temporal reasoning and fine-grained understanding tasks. To fill these gaps, we create 2.8M high-quality human-labeled. This release is nearly an order of magnitude larger than the largest existing video datasets.

<img src="https://huggingface.co/facebook/PE-Core-G14-448/resolve/main/docs/plm_cover.png" style="width: 100%; margin: 0 auto; display: block;" />

We provide the training and evaluation code at [perception_models codebase](https://github.com/facebookresearch/perception_models). You can find more details in the GitHub repo.

| Resource | Description | Documentation |
| --- | --- | --- |
| **Evaluation** | Evaluation of PLM using lmms-eval | [`docs/evaluation.md`](https://github.com/facebookresearch/perception_models/blob/main/apps/plm/docs/evaluation.md) |
| **Training / Finetuning** | Training and finetuning instructions for PLM | [`docs/training.md`](https://github.com/facebookresearch/perception_models/blob/main/apps/plm/docs/training.md) |
| **PLM-VideoBench** | Evaluation on PLM-VideoBench using lmms-eval | [`docs/plm_videobench.md`](https://github.com/facebookresearch/perception_models/blob/main/apps/plm/docs/plm_videobench.md) |
| **End-to-End Finetuning Example** | End-to-end finetuning example on radiology images | [`docs/finetune_example.md`](https://github.com/facebookresearch/perception_models/blob/main/apps/plm/docs/finetune_example.md) |
| **Generating Response** | Generate responses using a trained model with `generate.py` | [`generate.py`](https://github.com/facebookresearch/perception_models/blob/main/apps/plm/generate.py) |

## PLM Image Benchmark Results

| Model  | DocVQA | ChartQA | TextVQA | InfoQA | AI2D  | OCRBench | COCO | Nocap | Flickr | MMMU | VQAv2 | OKVQA | VizWiz | MME | SEED | BLINK | CVBench | RealWorldQA | VSR | POPE |
|:---------:|:--------:|:---------:|:---------:|:--------:|:------:|:----------:|:------------:|:-------------:|:--------------:|:------:|:-------:|:--------:|:--------:|:-----:|:------:|:-------:|:----------:|:-------------:|:-----:|:------:|
| PLM1B  | 90.7   | 78.6    | 82.1    | 63.0   | 84.9 | 807      | 138.6      | 124.2       | 100.5        | 34.8 | 81.7  | 61.0   | 59.7   | 1603| 76.3 | 46.8  | 73.8     | 67.1        | 68.8| 88.4 |
| PLM3B  | 93.8   | 84.3    | 84.3    | 74.6   | 90.9 | 830      | 144.9      | 126.5       | 98.0         | 41.2 | 84.3  | 66.8   | 64.0   | 1879| 78.5 | 55.4  | 81.4     | 72.4        | 80.4| 88.7 |
| PLM8B  | 94.6   | 85.5    | 86.5    | 80.9   | 92.7 | 870      | 146.7      | 129.9       | 105.6        | 46.1 | 85.6  | 69.6   | 67.0   | 1989| 79.3 | 56.0  | 81.3     | 75.0        | 82.8| 89.9 |

## PLM Video Benchmark Results

| Model  | VATEX                    | DREAM&nbsp;1K      | How2QA       | MVBench      | NExTQA      | PerceptionTest&nbsp;(test) | STAR       | TVQA       | VideoMME        | TVBench      | ActivityNetQA   | EgoSchema&nbsp;(test) | TemporalBench    | TOMATO     | MotionBench&nbsp;(dev) | TempCompass&nbsp;(MCQ) | CGBench&nbsp;(clue) | Charades&nbsp;STA   | VideoHallucer   | Halluc.&nbsp;EventHallusion |
|:-------------:|:---------------------------:|:-----------------------:|:---------------------:|:-------------:|:-------------:|:--------------------------:|:----------:|:----------:|:----------------:|:-------------:|:--------------------:|:----------------------:|:---------------------:|:------------:|:------------------------:|:-----------------------:|:---------------------:|:-------------------:|:-------------------------------:|:--------------------------------:|
| PLM1B  | 92.5 | 34.3 | 86.4 | 70.1 | 80.3 | 72.7 | 83.7 | 50.3 | 49.2 | 50.4 | 62.5 | 60.4 | 18.2 | 25.5 | 52.2 | 64.6 | 43.6 | 55.2 | 49.2 | 79.5 |
| PLM3B  | 96.1 | 37.4 | 89.4 | 74.7 | 83.4 | 79.3 | 84.8 | 55.3 | 54.9 | 58.9 | 66.2 | 66.9 | 23.4 | 30.9 | 60.4 | 69.3 | 47.2 | 57.7 | 55.5 | 76.5 |
| PLM8B  | 99.7 | 35.9 | 90.7 | 77.1 | 84.1 | 82.7 | 84.9 | 59.3 | 58.3 | 63.5 | 67.3 | 68.8 | 28.3 | 33.2 | 61.4 | 72.7 | 46.4 | 58.6 | 57.7 | 77.3 |

## PLM Usage

Files here work with huggingface transformers library while original checkpoints that work with [perception_models](https://github.com/facebookresearch/perception_models) are under `original/`.

To use latest transformers library,
```
pip install --upgrade git+https://github.com/huggingface/transformers.git
```

PLM example with image input:
```
from transformers import AutoProcessor, AutoModelForImageTextToText
from huggingface_hub import hf_hub_download

MODEL_PATH = "facebook/Perception-LM-1B"
processor = AutoProcessor.from_pretrained(MODEL_PATH, use_fast=True)
model = AutoModelForImageTextToText.from_pretrained(MODEL_PATH).to("cuda")
test_image_file = hf_hub_download(
            repo_id="shumingh/perception_lm_test_images",
            filename="14496_0.PNG",
            repo_type="dataset",
)
conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "url": test_image_file,
            },
            {"type": "text", "text": "Describe the bar plot in the image."},
        ],
    }
]

inputs = processor.apply_chat_template(
    [conversation],
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
)
inputs = inputs.to(model.device)
generate_ids = model.generate(**inputs, max_new_tokens=256)
input_length = inputs["input_ids"].shape[1]
generate_ids_without_inputs = generate_ids[:, input_length:]

for output in processor.batch_decode(generate_ids_without_inputs, skip_special_tokens=True):
    print(output)
```

PLM example with video input:
```
from transformers import AutoProcessor, AutoModelForImageTextToText
from huggingface_hub import hf_hub_download

MODEL_PATH = "facebook/Perception-LM-1B"
processor = AutoProcessor.from_pretrained(MODEL_PATH, use_fast=True)
model = AutoModelForImageTextToText.from_pretrained(MODEL_PATH).to("cuda")

video_file = hf_hub_download(
    repo_id="shumingh/perception_lm_test_videos",
    filename="GUWR5TyiY-M_000012_000022.mp4",
    repo_type="dataset",
)
conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "video",
                "url": video_file,
            },
            {"type": "text", "text": "Can you describe the video in detail?"},
        ],
    }
]
inputs = processor.apply_chat_template(
    [conversation],
    num_frames=32,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    video_load_backend="decord",
)
inputs = inputs.to(model.device)
generate_ids = model.generate(**inputs, max_new_tokens=256)
input_length = inputs["input_ids"].shape[1]
generate_ids_without_inputs = generate_ids[:, input_length:]

for output in processor.batch_decode(
    generate_ids_without_inputs, skip_special_tokens=True
):
    print(output)
```

PLM Simple Fine-tuning Example
```
import torch
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model
from transformers import AutoProcessor, BitsAndBytesConfig, AutoModelForImageTextToText
from transformers import TrainingArguments, Trainer
from datasets import load_dataset
from torch.nn.utils.rnn import pad_sequence


USE_LORA = False
USE_QLORA = False

model_id = "facebook/Perception-LM-1B"

processor = AutoProcessor.from_pretrained(model_id)


# Default is "thumb+tile" which corresponds to a max of 36 tiles
# We use "vanilla" which corresponds to a single tile here 
# 1) to save memory and 2) to simplify demo code
processor.image_processor.vision_input_type = "vanilla"


if USE_QLORA or USE_LORA:
    lora_config = LoraConfig(
        r=8,
        lora_alpha=8,
        lora_dropout=0.1,
        target_modules=[
            "down_proj",
            "o_proj",
            "k_proj",
            "q_proj",
            "gate_proj",
            "up_proj",
            "v_proj",
        ],
        use_dora=False if USE_QLORA else True,
        init_lora_weights="gaussian",
    )
    lora_config.inference_mode = False
    if USE_QLORA:
        bnb_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_compute_dtype=torch.bfloat16,
        )

    model = AutoModelForImageTextToText.from_pretrained(
        model_id,
        quantization_config=bnb_config if USE_QLORA else None,
        device_map="auto",
    )
    model.add_adapter(lora_config)
    model.enable_adapters()
    model = prepare_model_for_kbit_training(model)
    model = get_peft_model(model, lora_config)
    print(model.get_nb_trainable_parameters())
else:
    model = AutoModelForImageTextToText.from_pretrained(
        model_id,
        torch_dtype=torch.bfloat16,
    ).to("cuda")

    # if you'd like to only fine-tune LLM
    for param in model.model.vision_tower.parameters():
        param.requires_grad = False

peak_mem = torch.cuda.max_memory_allocated()
print(f"The model as is is holding: {peak_mem / 1024**3:.2f} of GPU RAM")

ds = load_dataset("unsloth/Radiology_mini")
split_ds = ds["train"].train_test_split(test_size=0.1)
train_ds = split_ds["train"]
print(f"prompt:  {train_ds[0]['caption']}, image_id: {train_ds[0]['image_id']}")


image_token_id = processor.tokenizer.image_token_id


def collate_fn(examples):
    instances = []
    for example in examples:
        caption = example["caption"]

        user_content = [
            {
                "type": "text",
                "text": "You are an expert radiographer. Describe accurately what you see in this image.",
            }
        ]
        user_content.append({"type": "image", "image": example["image"]})

        messages = [
            {"role": "user", "content": user_content},
            {"role": "assistant", "content": [{"type": "text", "text": f"{caption}"}]},
        ]

        instance = (
            processor.apply_chat_template(
                messages,
                add_generation_prompt=True,
                tokenize=True,
                return_dict=True,
                return_tensors="pt",
            )
            .to("cuda")
            .to(model.dtype)
        )
        instances.append(instance)

    input_ids = pad_sequence(
        [inst["input_ids"].squeeze(0) for inst in instances],
        batch_first=True,
        padding_value=processor.tokenizer.pad_token_id,
    )
    attention_mask = pad_sequence(
        [inst["attention_mask"].squeeze(0) for inst in instances],
        batch_first=True,
        padding_value=0,
    )
    labels = pad_sequence(
        [inst["input_ids"].squeeze(0).clone() for inst in instances],
        batch_first=True,
        padding_value=-100,
    )
    pixel_values = torch.cat(
        [inst["pixel_values"] for inst in instances], dim=0
    )

    labels[labels == image_token_id] = -100

    out = {
        "input_ids": input_ids,
        "attention_mask": attention_mask,
        "labels": labels,
        "pixel_values": pixel_values,
    }

    return out


model_name = model_id.split("/")[-1]

training_args = TrainingArguments(
    num_train_epochs=1,
    per_device_train_batch_size=8,
    gradient_accumulation_steps=1,
    warmup_steps=50,
    learning_rate=1e-4,
    weight_decay=0.01,
    logging_steps=25,
    save_strategy="steps",
    save_steps=250,
    save_total_limit=1,
    optim="adamw_torch",  # for 8-bit, keep paged_adamw_8bit, else adamw_hf
    bf16=True,
    output_dir=f"./{model_name}-radiology-mini",
    hub_model_id=f"{model_name}-radiology-mini",
    remove_unused_columns=False,
    report_to="tensorboard",
    dataloader_pin_memory=False,
)

trainer = Trainer(
    model=model,
    args=training_args,
    data_collator=collate_fn,
    train_dataset=train_ds,
)

trainer.train()
```

# Citation

If you find our code useful for your research, please consider citing:

```
@article{cho2025PerceptionLM,
  title={PerceptionLM: Open-Access Data and Models for Detailed Visual Understanding},
  author={Jang Hyun Cho and Andrea Madotto and Effrosyni Mavroudi and Triantafyllos Afouras and Tushar Nagarajan and Muhammad Maaz and Yale Song and Tengyu Ma and Shuming Hu and Hanoona Rasheed and Peize Sun and Po-Yao Huang and Daniel Bolya and Suyog Jain and Miguel Martin and Huiyu Wang and Nikhila Ravi and Shashank Jain and Temmy Stark and Shane Moon and Babak Damavandi and Vivian Lee and Andrew Westbury and Salman Khan and Philipp Kr\"{a}henb\"{u}hl and Piotr Doll{\'a}r and Lorenzo Torresani and Kristen Grauman and Christoph Feichtenhofer},
  journal={arXiv},
  year={2025}
}

@article{bolya2025PerceptionEncoder,
  title={Perception Encoder: The best visual embeddings are not at the output of the network},
  author={Daniel Bolya and Po-Yao Huang and Peize Sun and Jang Hyun Cho and Andrea Madotto and Chen Wei and Tengyu Ma and Jiale Zhi and Jathushan Rajasegaran and Hanoona Rasheed and Junke Wang and Marco Monteiro and Hu Xu and Shiyu Dong and Nikhila Ravi and Daniel Li and Piotr Doll{\'a}r and Christoph Feichtenhofer},
  journal={arXiv},
  year={2025}
}
```