auto_docstring.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  1. # coding=utf-8
  2. # Copyright 2025 HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import inspect
  16. import os
  17. import textwrap
  18. from pathlib import Path
  19. from typing import Optional, Union, get_args
  20. import regex as re
  21. from .doc import (
  22. MODELS_TO_PIPELINE,
  23. PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS,
  24. PT_SAMPLE_DOCSTRINGS,
  25. _prepare_output_docstrings,
  26. )
  27. from .generic import ModelOutput
  28. PATH_TO_TRANSFORMERS = Path("src").resolve() / "transformers"
  29. AUTODOC_FILES = [
  30. "configuration_*.py",
  31. "modeling_*.py",
  32. "tokenization_*.py",
  33. "processing_*.py",
  34. "image_processing_*_fast.py",
  35. "image_processing_*.py",
  36. "feature_extractor_*.py",
  37. ]
  38. PLACEHOLDER_TO_AUTO_MODULE = {
  39. "image_processor_class": ("image_processing_auto", "IMAGE_PROCESSOR_MAPPING_NAMES"),
  40. "video_processor_class": ("video_processing_auto", "VIDEO_PROCESSOR_MAPPING_NAMES"),
  41. "feature_extractor_class": ("feature_extraction_auto", "FEATURE_EXTRACTOR_MAPPING_NAMES"),
  42. "processor_class": ("processing_auto", "PROCESSOR_MAPPING_NAMES"),
  43. "config_class": ("configuration_auto", "CONFIG_MAPPING_NAMES"),
  44. }
  45. UNROLL_KWARGS_METHODS = {
  46. "preprocess",
  47. }
  48. UNROLL_KWARGS_CLASSES = {
  49. "ImageProcessorFast",
  50. }
  51. HARDCODED_CONFIG_FOR_MODELS = {
  52. "openai": "OpenAIGPTConfig",
  53. "x-clip": "XCLIPConfig",
  54. "kosmos2": "Kosmos2Config",
  55. "kosmos2-5": "Kosmos2_5Config",
  56. "donut": "DonutSwinConfig",
  57. "esmfold": "EsmConfig",
  58. }
  59. _re_checkpoint = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)")
  60. class ImageProcessorArgs:
  61. images = {
  62. "description": """
  63. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  64. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  65. """,
  66. "shape": None,
  67. }
  68. videos = {
  69. "description": """
  70. Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
  71. passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
  72. """,
  73. "shape": None,
  74. }
  75. do_resize = {
  76. "description": """
  77. Whether to resize the image.
  78. """,
  79. "shape": None,
  80. }
  81. size = {
  82. "description": """
  83. Describes the maximum input dimensions to the model.
  84. """,
  85. "shape": None,
  86. }
  87. default_to_square = {
  88. "description": """
  89. Whether to default to a square image when resizing, if size is an int.
  90. """,
  91. "shape": None,
  92. }
  93. resample = {
  94. "description": """
  95. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
  96. has an effect if `do_resize` is set to `True`.
  97. """,
  98. "shape": None,
  99. }
  100. do_center_crop = {
  101. "description": """
  102. Whether to center crop the image.
  103. """,
  104. "shape": None,
  105. }
  106. crop_size = {
  107. "description": """
  108. Size of the output image after applying `center_crop`.
  109. """,
  110. "shape": None,
  111. }
  112. do_pad = {
  113. "description": """
  114. Whether to pad the image. Padding is done either to the largest size in the batch
  115. or to a fixed square size per image. The exact padding strategy depends on the model.
  116. """,
  117. "shape": None,
  118. }
  119. pad_size = {
  120. "description": """
  121. The size in `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
  122. provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
  123. height and width in the batch. Applied only when `do_pad=True.`
  124. """,
  125. "shape": None,
  126. }
  127. do_rescale = {
  128. "description": """
  129. Whether to rescale the image.
  130. """,
  131. "shape": None,
  132. }
  133. rescale_factor = {
  134. "description": """
  135. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  136. """,
  137. "shape": None,
  138. }
  139. do_normalize = {
  140. "description": """
  141. Whether to normalize the image.
  142. """,
  143. "shape": None,
  144. }
  145. image_mean = {
  146. "description": """
  147. Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
  148. """,
  149. "shape": None,
  150. }
  151. image_std = {
  152. "description": """
  153. Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
  154. `True`.
  155. """,
  156. "shape": None,
  157. }
  158. do_convert_rgb = {
  159. "description": """
  160. Whether to convert the image to RGB.
  161. """,
  162. "shape": None,
  163. }
  164. return_tensors = {
  165. "description": """
  166. Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
  167. """,
  168. "shape": None,
  169. }
  170. data_format = {
  171. "description": """
  172. Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.
  173. """,
  174. "shape": None,
  175. }
  176. input_data_format = {
  177. "description": """
  178. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  179. from the input image. Can be one of:
  180. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  181. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  182. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  183. """,
  184. "shape": None,
  185. }
  186. device = {
  187. "description": """
  188. The device to process the images on. If unset, the device is inferred from the input images.
  189. """,
  190. "shape": None,
  191. }
  192. disable_grouping = {
  193. "description": """
  194. Whether to disable grouping of images by size to process them individually and not in batches.
  195. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on
  196. empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  197. """,
  198. "shape": None,
  199. }
  200. class ModelArgs:
  201. labels = {
  202. "description": """
  203. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  204. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  205. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  206. """,
  207. "shape": "of shape `(batch_size, sequence_length)`",
  208. }
  209. num_logits_to_keep = {
  210. "description": """
  211. Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
  212. `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
  213. token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
  214. """,
  215. "shape": None,
  216. }
  217. input_ids = {
  218. "description": """
  219. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
  220. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  221. [`PreTrainedTokenizer.__call__`] for details.
  222. [What are input IDs?](../glossary#input-ids)
  223. """,
  224. "shape": "of shape `(batch_size, sequence_length)`",
  225. }
  226. input_values = {
  227. "description": """
  228. Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
  229. into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
  230. (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
  231. To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
  232. into a tensor of type `torch.FloatTensor`. See [`{processor_class}.__call__`] for details.
  233. """,
  234. "shape": "of shape `(batch_size, sequence_length)`",
  235. }
  236. attention_mask = {
  237. "description": """
  238. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  239. - 1 for tokens that are **not masked**,
  240. - 0 for tokens that are **masked**.
  241. [What are attention masks?](../glossary#attention-mask)
  242. """,
  243. "shape": "of shape `(batch_size, sequence_length)`",
  244. }
  245. head_mask = {
  246. "description": """
  247. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  248. - 1 indicates the head is **not masked**,
  249. - 0 indicates the head is **masked**.
  250. """,
  251. "shape": "of shape `(num_heads,)` or `(num_layers, num_heads)`",
  252. }
  253. cross_attn_head_mask = {
  254. "description": """
  255. Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
  256. - 1 indicates the head is **not masked**,
  257. - 0 indicates the head is **masked**.
  258. """,
  259. "shape": "of shape `(num_layers, num_heads)`",
  260. }
  261. decoder_attention_mask = {
  262. "description": """
  263. Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to
  264. make sure the model can only look at previous inputs in order to predict the future.
  265. """,
  266. "shape": "of shape `(batch_size, target_sequence_length)`",
  267. }
  268. decoder_head_mask = {
  269. "description": """
  270. Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
  271. - 1 indicates the head is **not masked**,
  272. - 0 indicates the head is **masked**.
  273. """,
  274. "shape": "of shape `(decoder_layers, decoder_attention_heads)`",
  275. }
  276. encoder_hidden_states = {
  277. "description": """
  278. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
  279. if the model is configured as a decoder.
  280. """,
  281. "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
  282. }
  283. encoder_attention_mask = {
  284. "description": """
  285. Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  286. the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
  287. - 1 for tokens that are **not masked**,
  288. - 0 for tokens that are **masked**.
  289. """,
  290. "shape": "of shape `(batch_size, sequence_length)`",
  291. }
  292. token_type_ids = {
  293. "description": """
  294. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  295. - 0 corresponds to a *sentence A* token,
  296. - 1 corresponds to a *sentence B* token.
  297. [What are token type IDs?](../glossary#token-type-ids)
  298. """,
  299. "shape": "of shape `(batch_size, sequence_length)`",
  300. }
  301. position_ids = {
  302. "description": """
  303. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.
  304. [What are position IDs?](../glossary#position-ids)
  305. """,
  306. "shape": "of shape `(batch_size, sequence_length)`",
  307. }
  308. past_key_values = {
  309. "description": """
  310. Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
  311. blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
  312. returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  313. Only [`~cache_utils.Cache`] instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  314. If no `past_key_values` are passed, [`~cache_utils.DynamicCache`] will be initialized by default.
  315. The model will output the same cache format that is fed as input.
  316. If `past_key_values` are used, the user is expected to input only unprocessed `input_ids` (those that don't
  317. have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids`
  318. of shape `(batch_size, sequence_length)`.
  319. """,
  320. "shape": None,
  321. }
  322. inputs_embeds = {
  323. "description": """
  324. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  325. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  326. model's internal embedding lookup matrix.
  327. """,
  328. "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
  329. }
  330. decoder_input_ids = {
  331. "description": """
  332. Indices of decoder input sequence tokens in the vocabulary.
  333. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  334. [`PreTrainedTokenizer.__call__`] for details.
  335. [What are decoder input IDs?](../glossary#decoder-input-ids)
  336. """,
  337. "shape": "of shape `(batch_size, target_sequence_length)`",
  338. }
  339. decoder_inputs_embeds = {
  340. "description": """
  341. Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
  342. representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
  343. input (see `past_key_values`). This is useful if you want more control over how to convert
  344. `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
  345. If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
  346. of `inputs_embeds`.
  347. """,
  348. "shape": "of shape `(batch_size, target_sequence_length, hidden_size)`",
  349. }
  350. use_cache = {
  351. "description": """
  352. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  353. `past_key_values`).
  354. """,
  355. "shape": None,
  356. }
  357. output_attentions = {
  358. "description": """
  359. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  360. tensors for more detail.
  361. """,
  362. "shape": None,
  363. }
  364. output_hidden_states = {
  365. "description": """
  366. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  367. more detail.
  368. """,
  369. "shape": None,
  370. }
  371. return_dict = {
  372. "description": """
  373. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  374. """,
  375. "shape": None,
  376. }
  377. cache_position = {
  378. "description": """
  379. Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
  380. this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
  381. the complete sequence length.
  382. """,
  383. "shape": "of shape `(sequence_length)`",
  384. }
  385. hidden_states = {
  386. "description": """ input to the layer of shape `(batch, seq_len, embed_dim)""",
  387. "shape": None,
  388. }
  389. interpolate_pos_encoding = {
  390. "description": """
  391. Whether to interpolate the pre-trained position encodings.
  392. """,
  393. "shape": None,
  394. }
  395. position_embeddings = {
  396. "description": """
  397. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  398. with `head_dim` being the embedding dimension of each attention head.
  399. """,
  400. "shape": None,
  401. }
  402. config = {
  403. "description": """
  404. Model configuration class with all the parameters of the model. Initializing with a config file does not
  405. load the weights associated with the model, only the configuration. Check out the
  406. [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  407. """,
  408. "shape": None,
  409. }
  410. start_positions = {
  411. "description": """
  412. Labels for position (index) of the start of the labelled span for computing the token classification loss.
  413. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  414. are not taken into account for computing the loss.
  415. """,
  416. "shape": "of shape `(batch_size,)`",
  417. }
  418. end_positions = {
  419. "description": """
  420. Labels for position (index) of the end of the labelled span for computing the token classification loss.
  421. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  422. are not taken into account for computing the loss.
  423. """,
  424. "shape": "of shape `(batch_size,)`",
  425. }
  426. encoder_outputs = {
  427. "description": """
  428. Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
  429. `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
  430. hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
  431. """,
  432. "shape": None,
  433. }
  434. output_router_logits = {
  435. "description": """
  436. Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
  437. should not be returned during inference.
  438. """,
  439. "shape": None,
  440. }
  441. logits_to_keep = {
  442. "description": """
  443. If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
  444. `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
  445. token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
  446. If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
  447. This is useful when using packed tensor format (single dimension for batch and sequence length).
  448. """,
  449. "shape": None,
  450. }
  451. pixel_values = {
  452. "description": """
  453. The tensors corresponding to the input images. Pixel values can be obtained using
  454. [`{image_processor_class}`]. See [`{image_processor_class}.__call__`] for details ([`{processor_class}`] uses
  455. [`{image_processor_class}`] for processing images).
  456. """,
  457. "shape": "of shape `(batch_size, num_channels, image_size, image_size)`",
  458. }
  459. pixel_values_videos = {
  460. "description": """
  461. The tensors corresponding to the input video. Pixel values for videos can be obtained using
  462. [`{video_processor_class}`]. See [`{video_processor_class}.__call__`] for details ([`{processor_class}`] uses
  463. [`{video_processor_class}`] for processing videos).
  464. """,
  465. "shape": "of shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`",
  466. }
  467. vision_feature_layer = {
  468. "description": """
  469. The index of the layer to select the vision feature. If multiple indices are provided,
  470. the vision feature of the corresponding indices will be concatenated to form the
  471. vision features.
  472. """,
  473. "shape": None,
  474. }
  475. vision_feature_select_strategy = {
  476. "description": """
  477. The feature selection strategy used to select the vision feature from the vision backbone.
  478. Can be one of `"default"` or `"full"`.
  479. """,
  480. "shape": None,
  481. }
  482. image_sizes = {
  483. "description": """
  484. The sizes of the images in the batch, being (height, width) for each image.
  485. """,
  486. "shape": "of shape `(batch_size, 2)`",
  487. }
  488. pixel_mask = {
  489. "description": """
  490. Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
  491. - 1 for pixels that are real (i.e. **not masked**),
  492. - 0 for pixels that are padding (i.e. **masked**).
  493. [What are attention masks?](../glossary#attention-mask)
  494. """,
  495. "shape": "of shape `(batch_size, height, width)`",
  496. }
  497. input_features = {
  498. "description": """
  499. The tensors corresponding to the input audio features. Audio features can be obtained using
  500. [`{feature_extractor_class}`]. See [`{feature_extractor_class}.__call__`] for details ([`{processor_class}`] uses
  501. [`{feature_extractor_class}`] for processing audios).
  502. """,
  503. "shape": "of shape `(batch_size, sequence_length, feature_dim)`",
  504. }
  505. class ModelOutputArgs:
  506. last_hidden_state = {
  507. "description": """
  508. Sequence of hidden-states at the output of the last layer of the model.
  509. """,
  510. "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
  511. }
  512. past_key_values = {
  513. "description": """
  514. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  515. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  516. `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
  517. input) to speed up sequential decoding.
  518. """,
  519. "shape": None,
  520. "additional_info": "returned when `use_cache=True` is passed or when `config.use_cache=True`",
  521. }
  522. hidden_states = {
  523. "description": """
  524. Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  525. one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
  526. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
  527. """,
  528. "shape": None,
  529. "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`",
  530. }
  531. attentions = {
  532. "description": """
  533. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  534. sequence_length)`.
  535. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  536. heads.
  537. """,
  538. "shape": None,
  539. "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
  540. }
  541. pooler_output = {
  542. "description": """
  543. Last layer hidden-state after a pooling operation on the spatial dimensions.
  544. """,
  545. "shape": "of shape `(batch_size, hidden_size)`",
  546. }
  547. cross_attentions = {
  548. "description": """
  549. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  550. sequence_length)`.
  551. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  552. weighted average in the cross-attention heads.
  553. """,
  554. "shape": None,
  555. "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
  556. }
  557. decoder_hidden_states = {
  558. "description": """
  559. Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  560. one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
  561. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
  562. """,
  563. "shape": None,
  564. "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`",
  565. }
  566. decoder_attentions = {
  567. "description": """
  568. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  569. sequence_length)`.
  570. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
  571. self-attention heads.
  572. """,
  573. "shape": None,
  574. "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
  575. }
  576. encoder_last_hidden_state = {
  577. "description": """
  578. Sequence of hidden-states at the output of the last layer of the encoder of the model.
  579. """,
  580. "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
  581. }
  582. encoder_hidden_states = {
  583. "description": """
  584. Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  585. one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
  586. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
  587. """,
  588. "shape": None,
  589. "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`",
  590. }
  591. encoder_attentions = {
  592. "description": """
  593. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  594. sequence_length)`.
  595. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  596. self-attention heads.
  597. """,
  598. "shape": None,
  599. "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
  600. }
  601. router_logits = {
  602. "description": """
  603. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
  604. Router logits of the model, useful to compute the auxiliary loss for Mixture of Experts models.
  605. """,
  606. "shape": None,
  607. "additional_info": "returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`",
  608. }
  609. router_probs = {
  610. "description": """
  611. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
  612. Raw router probabilities that are computed by MoE routers, these terms are used to compute the auxiliary
  613. loss and the z_loss for Mixture of Experts models.
  614. """,
  615. "shape": None,
  616. "additional_info": "returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`",
  617. }
  618. z_loss = {
  619. "description": """
  620. z_loss for the sparse modules.
  621. """,
  622. "shape": None,
  623. "additional_info": "returned when `labels` is provided",
  624. }
  625. aux_loss = {
  626. "description": """
  627. aux_loss for the sparse modules.
  628. """,
  629. "shape": None,
  630. "additional_info": "returned when `labels` is provided",
  631. }
  632. start_logits = {
  633. "description": """
  634. Span-start scores (before SoftMax).
  635. """,
  636. "shape": "of shape `(batch_size, sequence_length)`",
  637. }
  638. end_logits = {
  639. "description": """
  640. Span-end scores (before SoftMax).
  641. """,
  642. "shape": "of shape `(batch_size, sequence_length)`",
  643. }
  644. feature_maps = {
  645. "description": """
  646. Feature maps of the stages.
  647. """,
  648. "shape": "of shape `(batch_size, num_channels, height, width)`",
  649. }
  650. reconstruction = {
  651. "description": """
  652. Reconstructed / completed images.
  653. """,
  654. "shape": "of shape `(batch_size, num_channels, height, width)`",
  655. }
  656. spectrogram = {
  657. "description": """
  658. The predicted spectrogram.
  659. """,
  660. "shape": "of shape `(batch_size, sequence_length, num_bins)`",
  661. }
  662. predicted_depth = {
  663. "description": """
  664. Predicted depth for each pixel.
  665. """,
  666. "shape": "of shape `(batch_size, height, width)`",
  667. }
  668. sequences = {
  669. "description": """
  670. Sampled values from the chosen distribution.
  671. """,
  672. "shape": "of shape `(batch_size, num_samples, prediction_length)` or `(batch_size, num_samples, prediction_length, input_size)`",
  673. }
  674. params = {
  675. "description": """
  676. Parameters of the chosen distribution.
  677. """,
  678. "shape": "of shape `(batch_size, num_samples, num_params)`",
  679. }
  680. loc = {
  681. "description": """
  682. Shift values of each time series' context window which is used to give the model inputs of the same
  683. magnitude and then used to shift back to the original magnitude.
  684. """,
  685. "shape": "of shape `(batch_size,)` or `(batch_size, input_size)`",
  686. }
  687. scale = {
  688. "description": """
  689. Scaling values of each time series' context window which is used to give the model inputs of the same
  690. magnitude and then used to rescale back to the original magnitude.
  691. """,
  692. "shape": "of shape `(batch_size,)` or `(batch_size, input_size)`",
  693. }
  694. static_features = {
  695. "description": """
  696. Static features of each time series' in a batch which are copied to the covariates at inference time.
  697. """,
  698. "shape": "of shape `(batch_size, feature size)`",
  699. }
  700. embeddings = {
  701. "description": """
  702. Utterance embeddings used for vector similarity-based retrieval.
  703. """,
  704. "shape": "of shape `(batch_size, config.xvector_output_dim)`",
  705. }
  706. extract_features = {
  707. "description": """
  708. Sequence of extracted feature vectors of the last convolutional layer of the model.
  709. """,
  710. "shape": "of shape `(batch_size, sequence_length, conv_dim[-1])`",
  711. }
  712. projection_state = {
  713. "description": """
  714. Text embeddings before the projection layer, used to mimic the last hidden state of the teacher encoder.
  715. """,
  716. "shape": "of shape `(batch_size,config.project_dim)`",
  717. }
  718. image_hidden_states = {
  719. "description": """
  720. Image hidden states of the model produced by the vision encoder and after projecting the last hidden state.
  721. """,
  722. "shape": "of shape `(batch_size, num_images, sequence_length, hidden_size)`",
  723. }
  724. video_hidden_states = {
  725. "description": """
  726. Video hidden states of the model produced by the vision encoder and after projecting the last hidden state.
  727. """,
  728. "shape": "of shape `(batch_size * num_frames, num_images, sequence_length, hidden_size)`",
  729. }
  730. class ClassDocstring:
  731. PreTrainedModel = r"""
  732. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  733. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  734. etc.)
  735. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  736. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  737. and behavior.
  738. """
  739. Model = r"""
  740. The bare {model_name} Model outputting raw hidden-states without any specific head on top.
  741. """
  742. ForPreTraining = r"""
  743. The {model_name} Model with a specified pretraining head on top.
  744. """
  745. Decoder = r"""
  746. The bare {model_name} Decoder outputting raw hidden-states without any specific head on top.
  747. """
  748. TextModel = r"""
  749. The bare {model_name} Text Model outputting raw hidden-states without any specific head on to.
  750. """
  751. ForSequenceClassification = r"""
  752. The {model_name} Model with a sequence classification/regression head on top e.g. for GLUE tasks.
  753. """
  754. ForQuestionAnswering = r"""
  755. The {model_name} transformer with a span classification head on top for extractive question-answering tasks like
  756. SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
  757. """
  758. ForMultipleChoice = r"""
  759. The {model_name} Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
  760. softmax) e.g. for RocStories/SWAG tasks.
  761. """
  762. ForMaskedLM = r"""
  763. The {model_name} Model with a `language modeling` head on top."
  764. """
  765. ForTokenClassification = r"""
  766. The {model_name} transformer with a token classification head on top (a linear layer on top of the hidden-states
  767. output) e.g. for Named-Entity-Recognition (NER) tasks.
  768. """
  769. ForConditionalGeneration = r"""
  770. The {model_name} Model for token generation conditioned on other modalities (e.g. image-text-to-text generation).
  771. """
  772. ForCausalLM = r"""
  773. The {model_name} Model for causal language modeling.
  774. """
  775. ImageProcessorFast = r"""
  776. Constructs a fast {model_name} image processor.
  777. """
  778. Backbone = r"""
  779. The {model_name} backbone.
  780. """
  781. ForImageClassification = r"""
  782. The {model_name} Model with an image classification head on top e.g. for ImageNet.
  783. """
  784. ForSemanticSegmentation = r"""
  785. The {model_name} Model with a semantic segmentation head on top e.g. for ADE20K, CityScapes.
  786. """
  787. ForAudioClassification = r"""
  788. The {model_name} Model with an audio classification head on top (a linear layer on top of the pooled
  789. output).
  790. """
  791. ForAudioFrameClassification = r"""
  792. The {model_name} Model with a frame classification head on top for tasks like Speaker Diarization.
  793. """
  794. ForPrediction = r"""
  795. The {model_name} Model with a distribution head on top for time-series forecasting.
  796. """
  797. WithProjection = r"""
  798. The {model_name} Model with a projection layer on top (a linear layer on top of the pooled output).
  799. """
  800. class ClassAttrs:
  801. # fmt: off
  802. base_model_prefix = r"""
  803. A string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.
  804. """
  805. supports_gradient_checkpointing = r"""
  806. Whether the model supports gradient checkpointing or not. Gradient checkpointing is a memory-saving technique that trades compute for memory, by storing only a subset of activations (checkpoints) and recomputing the activations that are not stored during the backward pass.
  807. """
  808. _no_split_modules = r"""
  809. Layers of modules that should not be split across devices should be added to `_no_split_modules`. This can be useful for modules that contains skip connections or other operations that are not compatible with splitting the module across devices. Setting this attribute will enable the use of `device_map="auto"` in the `from_pretrained` method.
  810. """
  811. _skip_keys_device_placement = r"""
  812. A list of keys to ignore when moving inputs or outputs between devices when using the `accelerate` library.
  813. """
  814. _supports_flash_attn = r"""
  815. Whether the model's attention implementation supports FlashAttention.
  816. """
  817. _supports_sdpa = r"""
  818. Whether the model's attention implementation supports SDPA (Scaled Dot Product Attention).
  819. """
  820. _supports_flex_attn = r"""
  821. Whether the model's attention implementation supports FlexAttention.
  822. """
  823. _can_compile_fullgraph = r"""
  824. Whether the model can `torch.compile` fullgraph without graph breaks. Models will auto-compile if this flag is set to `True`
  825. in inference, if a compilable cache is used.
  826. """
  827. _supports_attention_backend = r"""
  828. Whether the model supports attention interface functions. This flag signal that the model can be used as an efficient backend in TGI and vLLM.
  829. """
  830. _tied_weights_keys = r"""
  831. A list of `state_dict` keys that are potentially tied to another key in the state_dict.
  832. """
  833. # fmt: on
  834. ARGS_TO_IGNORE = {"self", "kwargs", "args", "deprecated_arguments"}
  835. def get_indent_level(func):
  836. # Use this instead of `inspect.getsource(func)` as getsource can be very slow
  837. return (len(func.__qualname__.split(".")) - 1) * 4
  838. def equalize_indent(docstring, indent_level):
  839. """
  840. Adjust the indentation of a docstring to match the specified indent level.
  841. """
  842. # fully dedent the docstring
  843. docstring = "\n".join([line.lstrip() for line in docstring.splitlines()])
  844. return textwrap.indent(docstring, " " * indent_level)
  845. def set_min_indent(docstring, indent_level):
  846. """
  847. Adjust the indentation of a docstring to match the specified indent level.
  848. """
  849. return textwrap.indent(textwrap.dedent(docstring), " " * indent_level)
  850. def parse_shape(docstring):
  851. shape_pattern = re.compile(r"(of shape\s*(?:`.*?`|\(.*?\)))")
  852. match = shape_pattern.search(docstring)
  853. if match:
  854. return " " + match.group(1)
  855. return None
  856. def parse_default(docstring):
  857. default_pattern = re.compile(r"(defaults to \s*[^)]*)")
  858. match = default_pattern.search(docstring)
  859. if match:
  860. return " " + match.group(1)
  861. return None
  862. def parse_docstring(docstring, max_indent_level=0, return_intro=False):
  863. """
  864. Parse the docstring to extract the Args section and return it as a dictionary.
  865. The docstring is expected to be in the format:
  866. Args:
  867. arg1 (type):
  868. Description of arg1.
  869. arg2 (type):
  870. Description of arg2.
  871. # This function will also return the remaining part of the docstring after the Args section.
  872. Returns:/Example:
  873. ...
  874. """
  875. match = re.search(r"(?m)^([ \t]*)(?=Example|Return)", docstring)
  876. if match:
  877. remainder_docstring = docstring[match.start() :]
  878. docstring = docstring[: match.start()]
  879. else:
  880. remainder_docstring = ""
  881. args_pattern = re.compile(r"(?:Args:)(\n.*)?(\n)?$", re.DOTALL)
  882. args_match = args_pattern.search(docstring)
  883. # still try to find args description in the docstring, if args are not preceded by "Args:"
  884. docstring_intro = None
  885. if args_match:
  886. docstring_intro = docstring[: args_match.start()]
  887. if docstring_intro.split("\n")[-1].strip() == '"""':
  888. docstring_intro = "\n".join(docstring_intro.split("\n")[:-1])
  889. if docstring_intro.split("\n")[0].strip() == 'r"""' or docstring_intro.split("\n")[0].strip() == '"""':
  890. docstring_intro = "\n".join(docstring_intro.split("\n")[1:])
  891. if docstring_intro.strip() == "":
  892. docstring_intro = None
  893. args_section = args_match.group(1).lstrip("\n") if args_match else docstring
  894. if args_section.split("\n")[-1].strip() == '"""':
  895. args_section = "\n".join(args_section.split("\n")[:-1])
  896. if args_section.split("\n")[0].strip() == 'r"""' or args_section.split("\n")[0].strip() == '"""':
  897. args_section = "\n".join(args_section.split("\n")[1:])
  898. args_section = set_min_indent(args_section, 0)
  899. params = {}
  900. if args_section:
  901. param_pattern = re.compile(
  902. # |--- Group 1 ---|| Group 2 ||- Group 3 -||---------- Group 4 ----------|
  903. rf"^\s{{0,{max_indent_level}}}(\w+)\s*\(\s*([^, \)]*)(\s*.*?)\s*\)\s*:\s*((?:(?!\n^\s{{0,{max_indent_level}}}\w+\s*\().)*)",
  904. re.DOTALL | re.MULTILINE,
  905. )
  906. for match in param_pattern.finditer(args_section):
  907. param_name = match.group(1)
  908. param_type = match.group(2)
  909. # param_type = match.group(2).replace("`", "")
  910. additional_info = match.group(3)
  911. optional = "optional" in additional_info
  912. shape = parse_shape(additional_info)
  913. default = parse_default(additional_info)
  914. param_description = match.group(4).strip()
  915. # set first line of param_description to 4 spaces:
  916. param_description = re.sub(r"^", " " * 4, param_description, 1)
  917. param_description = f"\n{param_description}"
  918. params[param_name] = {
  919. "type": param_type,
  920. "description": param_description,
  921. "optional": optional,
  922. "shape": shape,
  923. "default": default,
  924. "additional_info": additional_info,
  925. }
  926. if params and remainder_docstring:
  927. remainder_docstring = "\n" + remainder_docstring
  928. remainder_docstring = set_min_indent(remainder_docstring, 0)
  929. if return_intro:
  930. return params, remainder_docstring, docstring_intro
  931. return params, remainder_docstring
  932. def contains_type(type_hint, target_type) -> tuple[bool, Optional[object]]:
  933. """
  934. Check if a "nested" type hint contains a specific target type,
  935. return the first-level type containing the target_type if found.
  936. """
  937. args = get_args(type_hint)
  938. if args == ():
  939. try:
  940. return issubclass(type_hint, target_type), type_hint
  941. except Exception:
  942. return issubclass(type(type_hint), target_type), type_hint
  943. found_type_tuple = [contains_type(arg, target_type)[0] for arg in args]
  944. found_type = any(found_type_tuple)
  945. if found_type:
  946. type_hint = args[found_type_tuple.index(True)]
  947. return found_type, type_hint
  948. def get_model_name(obj):
  949. """
  950. Get the model name from the file path of the object.
  951. """
  952. path = inspect.getsourcefile(obj)
  953. if path is None:
  954. return None
  955. if path.split(os.path.sep)[-3] != "models":
  956. return None
  957. file_name = path.split(os.path.sep)[-1]
  958. for file_type in AUTODOC_FILES:
  959. start = file_type.split("*")[0]
  960. end = file_type.split("*")[-1] if "*" in file_type else ""
  961. if file_name.startswith(start) and file_name.endswith(end):
  962. model_name_lowercase = file_name[len(start) : -len(end)]
  963. return model_name_lowercase
  964. print(f"🚨 Something went wrong trying to find the model name in the path: {path}")
  965. return "model"
  966. def get_placeholders_dict(placeholders: list, model_name: str) -> dict:
  967. """
  968. Get the dictionary of placeholders for the given model name.
  969. """
  970. # import here to avoid circular import
  971. from transformers.models import auto as auto_module
  972. placeholders_dict = {}
  973. for placeholder in placeholders:
  974. # Infer placeholders from the model name and the auto modules
  975. if placeholder in PLACEHOLDER_TO_AUTO_MODULE:
  976. try:
  977. place_holder_value = getattr(
  978. getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE[placeholder][0]),
  979. PLACEHOLDER_TO_AUTO_MODULE[placeholder][1],
  980. ).get(model_name, None)
  981. except ImportError:
  982. # In case a library is not installed, we don't want to fail the docstring generation
  983. place_holder_value = None
  984. if place_holder_value is not None:
  985. if isinstance(place_holder_value, (list, tuple)):
  986. place_holder_value = place_holder_value[0]
  987. placeholders_dict[placeholder] = place_holder_value if place_holder_value is not None else placeholder
  988. else:
  989. placeholders_dict[placeholder] = placeholder
  990. return placeholders_dict
  991. def format_args_docstring(docstring, model_name):
  992. """
  993. Replaces placeholders such as {image_processor_class} in the docstring with the actual values,
  994. deducted from the model name and the auto modules.
  995. """
  996. # first check if there are any placeholders in the docstring, if not return it as is
  997. placeholders = set(re.findall(r"{(.*?)}", docstring))
  998. if not placeholders:
  999. return docstring
  1000. # get the placeholders dictionary for the given model name
  1001. placeholders_dict = get_placeholders_dict(placeholders, model_name)
  1002. # replace the placeholders in the docstring with the values from the placeholders_dict
  1003. for placeholder, value in placeholders_dict.items():
  1004. if placeholder is not None:
  1005. try:
  1006. docstring = docstring.replace(f"{{{placeholder}}}", value)
  1007. except Exception:
  1008. pass
  1009. return docstring
  1010. def get_args_doc_from_source(args_classes: Union[object, list[object]]) -> dict:
  1011. if isinstance(args_classes, (list, tuple)):
  1012. args_classes_dict = {}
  1013. for args_class in args_classes:
  1014. args_classes_dict.update(args_class.__dict__)
  1015. return args_classes_dict
  1016. return args_classes.__dict__
  1017. def get_checkpoint_from_config_class(config_class):
  1018. checkpoint = None
  1019. # source code of `config_class`
  1020. # config_source = inspect.getsource(config_class)
  1021. config_source = config_class.__doc__
  1022. checkpoints = _re_checkpoint.findall(config_source)
  1023. # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
  1024. # For example, `('google-bert/bert-base-uncased', 'https://huggingface.co/google-bert/bert-base-uncased')`
  1025. for ckpt_name, ckpt_link in checkpoints:
  1026. # allow the link to end with `/`
  1027. ckpt_link = ckpt_link.removesuffix("/")
  1028. # verify the checkpoint name corresponds to the checkpoint link
  1029. ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}"
  1030. if ckpt_link == ckpt_link_from_name:
  1031. checkpoint = ckpt_name
  1032. break
  1033. return checkpoint
  1034. def add_intro_docstring(func, class_name, indent_level=0):
  1035. intro_docstring = ""
  1036. if func.__name__ == "forward":
  1037. intro_docstring = rf"""The [`{class_name}`] forward method, overrides the `__call__` special method.
  1038. <Tip>
  1039. Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]
  1040. instance afterwards instead of this since the former takes care of running the pre and post processing steps while
  1041. the latter silently ignores them.
  1042. </Tip>
  1043. """
  1044. intro_docstring = equalize_indent(intro_docstring, indent_level + 4)
  1045. return intro_docstring
  1046. def _get_model_info(func, parent_class):
  1047. """
  1048. Extract model information from a function or its parent class.
  1049. Args:
  1050. func (`function`): The function to extract information from
  1051. parent_class (`class`): Optional parent class of the function
  1052. """
  1053. # import here to avoid circular import
  1054. from transformers.models import auto as auto_module
  1055. # Get model name from either parent class or function
  1056. if parent_class is not None:
  1057. model_name_lowercase = get_model_name(parent_class)
  1058. else:
  1059. model_name_lowercase = get_model_name(func)
  1060. # Normalize model name if needed
  1061. if model_name_lowercase and model_name_lowercase not in getattr(
  1062. getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]),
  1063. PLACEHOLDER_TO_AUTO_MODULE["config_class"][1],
  1064. ):
  1065. model_name_lowercase = model_name_lowercase.replace("_", "-")
  1066. # Get class name from function's qualified name
  1067. class_name = func.__qualname__.split(".")[0]
  1068. # Get config class for the model
  1069. if model_name_lowercase is None:
  1070. config_class = None
  1071. else:
  1072. try:
  1073. config_class = getattr(
  1074. getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]),
  1075. PLACEHOLDER_TO_AUTO_MODULE["config_class"][1],
  1076. )[model_name_lowercase]
  1077. except KeyError:
  1078. if model_name_lowercase in HARDCODED_CONFIG_FOR_MODELS:
  1079. config_class = HARDCODED_CONFIG_FOR_MODELS[model_name_lowercase]
  1080. else:
  1081. config_class = "ModelConfig"
  1082. print(
  1083. f"🚨 Config not found for {model_name_lowercase}. You can manually add it to HARDCODED_CONFIG_FOR_MODELS in utils/auto_docstring.py"
  1084. )
  1085. return model_name_lowercase, class_name, config_class
  1086. def _process_parameter_type(param, param_name, func):
  1087. """
  1088. Process and format a parameter's type annotation.
  1089. Args:
  1090. param (`inspect.Parameter`): The parameter from the function signature
  1091. param_name (`str`): The name of the parameter
  1092. func (`function`): The function the parameter belongs to
  1093. """
  1094. optional = False
  1095. if param.annotation != inspect.Parameter.empty:
  1096. param_type = param.annotation
  1097. if "typing" in str(param_type):
  1098. param_type = "".join(str(param_type).split("typing.")).replace("transformers.", "~")
  1099. elif hasattr(param_type, "__module__"):
  1100. param_type = f"{param_type.__module__.replace('transformers.', '~').replace('builtins', '')}.{param.annotation.__name__}"
  1101. if param_type[0] == ".":
  1102. param_type = param_type[1:]
  1103. else:
  1104. if False:
  1105. print(
  1106. f"🚨 {param_type} for {param_name} of {func.__qualname__} in file {func.__code__.co_filename} has an invalid type"
  1107. )
  1108. if "ForwardRef" in param_type:
  1109. param_type = re.sub(r"ForwardRef\('([\w.]+)'\)", r"\1", param_type)
  1110. if "Optional" in param_type:
  1111. param_type = re.sub(r"Optional\[(.*?)\]", r"\1", param_type)
  1112. optional = True
  1113. else:
  1114. param_type = ""
  1115. return param_type, optional
  1116. def _get_parameter_info(param_name, documented_params, source_args_dict, param_type, optional):
  1117. """
  1118. Get parameter documentation details from the appropriate source.
  1119. Tensor shape, optional status and description are taken from the custom docstring in priority if available.
  1120. Type is taken from the function signature first, then from the custom docstring if missing from the signature
  1121. Args:
  1122. param_name (`str`): Name of the parameter
  1123. documented_params (`dict`): Dictionary of documented parameters (manually specified in the docstring)
  1124. source_args_dict (`dict`): Default source args dictionary to use if not in documented_params
  1125. param_type (`str`): Current parameter type (may be updated)
  1126. optional (`bool`): Whether the parameter is optional (may be updated)
  1127. """
  1128. description = None
  1129. shape = None
  1130. shape_string = ""
  1131. is_documented = True
  1132. additional_info = None
  1133. optional_string = r", *optional*" if optional else ""
  1134. if param_name in documented_params:
  1135. # Parameter is documented in the function's docstring
  1136. if (
  1137. param_type == ""
  1138. and documented_params[param_name].get("type", None) is not None
  1139. or documented_params[param_name]["additional_info"]
  1140. ):
  1141. param_type = documented_params[param_name]["type"]
  1142. optional = documented_params[param_name]["optional"]
  1143. shape = documented_params[param_name]["shape"]
  1144. shape_string = shape if shape else ""
  1145. additional_info = documented_params[param_name]["additional_info"] or ""
  1146. description = f"{documented_params[param_name]['description']}\n"
  1147. elif param_name in source_args_dict:
  1148. # Parameter is documented in ModelArgs or ImageProcessorArgs
  1149. shape = source_args_dict[param_name]["shape"]
  1150. shape_string = " " + shape if shape else ""
  1151. description = source_args_dict[param_name]["description"]
  1152. additional_info = source_args_dict[param_name].get("additional_info", None)
  1153. if additional_info:
  1154. additional_info = shape_string + optional_string + ", " + additional_info
  1155. else:
  1156. # Parameter is not documented
  1157. is_documented = False
  1158. return param_type, optional_string, shape_string, additional_info, description, is_documented
  1159. def _process_regular_parameters(
  1160. sig, func, class_name, documented_params, indent_level, undocumented_parameters, source_args_dict, parent_class
  1161. ):
  1162. """
  1163. Process all regular parameters (not kwargs parameters) from the function signature.
  1164. Args:
  1165. sig (`inspect.Signature`): Function signature
  1166. func (`function`): Function the parameters belong to
  1167. class_name (`str`): Name of the class
  1168. documented_params (`dict`): Dictionary of parameters that are already documented
  1169. indent_level (`int`): Indentation level
  1170. undocumented_parameters (`list`): List to append undocumented parameters to
  1171. """
  1172. docstring = ""
  1173. source_args_dict = (
  1174. get_args_doc_from_source([ModelArgs, ImageProcessorArgs]) if source_args_dict is None else source_args_dict
  1175. )
  1176. missing_args = {}
  1177. for param_name, param in sig.parameters.items():
  1178. # Skip parameters that should be ignored
  1179. if (
  1180. param_name in ARGS_TO_IGNORE
  1181. or param.kind == inspect.Parameter.VAR_POSITIONAL
  1182. or param.kind == inspect.Parameter.VAR_KEYWORD
  1183. ):
  1184. continue
  1185. # Process parameter type and optional status
  1186. param_type, optional = _process_parameter_type(param, param_name, func)
  1187. # Check for default value
  1188. param_default = ""
  1189. if param.default != inspect._empty and param.default is not None:
  1190. param_default = f", defaults to `{str(param.default)}`"
  1191. param_type, optional_string, shape_string, additional_info, description, is_documented = _get_parameter_info(
  1192. param_name, documented_params, source_args_dict, param_type, optional
  1193. )
  1194. if is_documented:
  1195. if param_name == "config":
  1196. if param_type == "":
  1197. param_type = f"[`{class_name}`]"
  1198. else:
  1199. param_type = f"[`{param_type.split('.')[-1]}`]"
  1200. # elif param_type == "" and False: # TODO: Enforce typing for all parameters
  1201. # print(f"🚨 {param_name} for {func.__qualname__} in file {func.__code__.co_filename} has no type")
  1202. param_type = param_type if "`" in param_type else f"`{param_type}`"
  1203. # Format the parameter docstring
  1204. if additional_info:
  1205. param_docstring = f"{param_name} ({param_type}{additional_info}):{description}"
  1206. else:
  1207. param_docstring = (
  1208. f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}"
  1209. )
  1210. docstring += set_min_indent(
  1211. param_docstring,
  1212. indent_level + 8,
  1213. )
  1214. else:
  1215. missing_args[param_name] = {
  1216. "type": param_type if param_type else "<fill_type>",
  1217. "optional": optional,
  1218. "shape": shape_string,
  1219. "description": description if description else "\n <fill_description>",
  1220. "default": param_default,
  1221. }
  1222. undocumented_parameters.append(
  1223. f"🚨 `{param_name}` is part of {func.__qualname__}'s signature, but not documented. Make sure to add it to the docstring of the function in {func.__code__.co_filename}."
  1224. )
  1225. return docstring, missing_args
  1226. def find_sig_line(lines, line_end):
  1227. parenthesis_count = 0
  1228. sig_line_end = line_end
  1229. found_sig = False
  1230. while not found_sig:
  1231. for char in lines[sig_line_end]:
  1232. if char == "(":
  1233. parenthesis_count += 1
  1234. elif char == ")":
  1235. parenthesis_count -= 1
  1236. if parenthesis_count == 0:
  1237. found_sig = True
  1238. break
  1239. sig_line_end += 1
  1240. return sig_line_end
  1241. def _process_kwargs_parameters(sig, func, parent_class, documented_kwargs, indent_level, undocumented_parameters):
  1242. """
  1243. Process **kwargs parameters if needed.
  1244. Args:
  1245. sig (`inspect.Signature`): Function signature
  1246. func (`function`): Function the parameters belong to
  1247. parent_class (`class`): Parent class of the function
  1248. documented_kwargs (`dict`): Dictionary of kwargs that are already documented
  1249. indent_level (`int`): Indentation level
  1250. undocumented_parameters (`list`): List to append undocumented parameters to
  1251. """
  1252. docstring = ""
  1253. source_args_dict = get_args_doc_from_source(ImageProcessorArgs)
  1254. # Check if we need to add typed kwargs description to the docstring
  1255. unroll_kwargs = func.__name__ in UNROLL_KWARGS_METHODS
  1256. if not unroll_kwargs and parent_class is not None:
  1257. # Check if the function has a parent class with unroll kwargs
  1258. unroll_kwargs = any(
  1259. unroll_kwargs_class in parent_class.__name__ for unroll_kwargs_class in UNROLL_KWARGS_CLASSES
  1260. )
  1261. if unroll_kwargs:
  1262. # get all unpackable "kwargs" parameters
  1263. kwargs_parameters = [
  1264. kwargs_param
  1265. for _, kwargs_param in sig.parameters.items()
  1266. if kwargs_param.kind == inspect.Parameter.VAR_KEYWORD
  1267. ]
  1268. for kwarg_param in kwargs_parameters:
  1269. # If kwargs not typed, skip
  1270. if kwarg_param.annotation == inspect.Parameter.empty:
  1271. continue
  1272. # Extract documentation for kwargs
  1273. kwargs_documentation = kwarg_param.annotation.__args__[0].__doc__
  1274. if kwargs_documentation is not None:
  1275. documented_kwargs = parse_docstring(kwargs_documentation)[0]
  1276. # Process each kwarg parameter
  1277. for param_name, param_type_annotation in kwarg_param.annotation.__args__[0].__annotations__.items():
  1278. param_type = str(param_type_annotation)
  1279. optional = False
  1280. # Process parameter type
  1281. if "typing" in param_type:
  1282. param_type = "".join(param_type.split("typing.")).replace("transformers.", "~")
  1283. else:
  1284. param_type = f"{param_type.replace('transformers.', '~').replace('builtins', '')}.{param_name}"
  1285. if "ForwardRef" in param_type:
  1286. param_type = re.sub(r"ForwardRef\('([\w.]+)'\)", r"\1", param_type)
  1287. if "Optional" in param_type:
  1288. param_type = re.sub(r"Optional\[(.*?)\]", r"\1", param_type)
  1289. optional = True
  1290. # Check for default value
  1291. param_default = ""
  1292. if parent_class is not None:
  1293. param_default = str(getattr(parent_class, param_name, ""))
  1294. param_default = f", defaults to `{param_default}`" if param_default != "" else ""
  1295. param_type, optional_string, shape_string, additional_info, description, is_documented = (
  1296. _get_parameter_info(param_name, documented_kwargs, source_args_dict, param_type, optional)
  1297. )
  1298. if is_documented:
  1299. # Check if type is missing
  1300. if param_type == "":
  1301. print(
  1302. f"🚨 {param_name} for {kwarg_param.annotation.__args__[0].__qualname__} in file {func.__code__.co_filename} has no type"
  1303. )
  1304. param_type = param_type if "`" in param_type else f"`{param_type}`"
  1305. # Format the parameter docstring
  1306. if additional_info:
  1307. docstring += set_min_indent(
  1308. f"{param_name} ({param_type}{additional_info}):{description}",
  1309. indent_level + 8,
  1310. )
  1311. else:
  1312. docstring += set_min_indent(
  1313. f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}",
  1314. indent_level + 8,
  1315. )
  1316. else:
  1317. undocumented_parameters.append(
  1318. f"🚨 `{param_name}` is part of {kwarg_param.annotation.__args__[0].__qualname__}, but not documented. Make sure to add it to the docstring of the function in {func.__code__.co_filename}."
  1319. )
  1320. return docstring
  1321. def _process_parameters_section(
  1322. func_documentation, sig, func, class_name, model_name_lowercase, parent_class, indent_level, source_args_dict
  1323. ):
  1324. """
  1325. Process the parameters section of the docstring.
  1326. Args:
  1327. func_documentation (`str`): Existing function documentation (manually specified in the docstring)
  1328. sig (`inspect.Signature`): Function signature
  1329. func (`function`): Function the parameters belong to
  1330. class_name (`str`): Name of the class the function belongs to
  1331. model_name_lowercase (`str`): Lowercase model name
  1332. parent_class (`class`): Parent class of the function (if any)
  1333. indent_level (`int`): Indentation level
  1334. """
  1335. # Start Args section
  1336. docstring = set_min_indent("Args:\n", indent_level + 4)
  1337. undocumented_parameters = []
  1338. documented_params = {}
  1339. documented_kwargs = {}
  1340. # Parse existing docstring if available
  1341. if func_documentation is not None:
  1342. documented_params, func_documentation = parse_docstring(func_documentation)
  1343. # Process regular parameters
  1344. param_docstring, missing_args = _process_regular_parameters(
  1345. sig, func, class_name, documented_params, indent_level, undocumented_parameters, source_args_dict, parent_class
  1346. )
  1347. docstring += param_docstring
  1348. # Process **kwargs parameters if needed
  1349. kwargs_docstring = _process_kwargs_parameters(
  1350. sig, func, parent_class, documented_kwargs, indent_level, undocumented_parameters
  1351. )
  1352. docstring += kwargs_docstring
  1353. # Report undocumented parameters
  1354. if len(undocumented_parameters) > 0:
  1355. print("\n".join(undocumented_parameters))
  1356. return docstring
  1357. def _process_returns_section(func_documentation, sig, config_class, indent_level):
  1358. """
  1359. Process the returns section of the docstring.
  1360. Args:
  1361. func_documentation (`str`): Existing function documentation (manually specified in the docstring)
  1362. sig (`inspect.Signature`): Function signature
  1363. config_class (`str`): Config class for the model
  1364. indent_level (`int`): Indentation level
  1365. """
  1366. return_docstring = ""
  1367. # Extract returns section from existing docstring if available
  1368. if (
  1369. func_documentation is not None
  1370. and (match_start := re.search(r"(?m)^([ \t]*)(?=Return)", func_documentation)) is not None
  1371. ):
  1372. match_end = re.search(r"(?m)^([ \t]*)(?=Example)", func_documentation)
  1373. if match_end:
  1374. return_docstring = func_documentation[match_start.start() : match_end.start()]
  1375. func_documentation = func_documentation[match_end.start() :]
  1376. else:
  1377. return_docstring = func_documentation[match_start.start() :]
  1378. func_documentation = ""
  1379. return_docstring = set_min_indent(return_docstring, indent_level + 4)
  1380. # Otherwise, generate return docstring from return annotation if available
  1381. elif sig.return_annotation is not None and sig.return_annotation != inspect._empty:
  1382. add_intro, return_annotation = contains_type(sig.return_annotation, ModelOutput)
  1383. return_docstring = _prepare_output_docstrings(return_annotation, config_class, add_intro=add_intro)
  1384. return_docstring = return_docstring.replace("typing.", "")
  1385. return_docstring = set_min_indent(return_docstring, indent_level + 4)
  1386. return return_docstring, func_documentation
  1387. def _process_example_section(
  1388. func_documentation, func, parent_class, class_name, model_name_lowercase, config_class, checkpoint, indent_level
  1389. ):
  1390. """
  1391. Process the example section of the docstring.
  1392. Args:
  1393. func_documentation (`str`): Existing function documentation (manually specified in the docstring)
  1394. func (`function`): Function being processed
  1395. parent_class (`class`): Parent class of the function
  1396. class_name (`str`): Name of the class
  1397. model_name_lowercase (`str`): Lowercase model name
  1398. config_class (`str`): Config class for the model
  1399. checkpoint: Checkpoint to use in examples
  1400. indent_level (`int`): Indentation level
  1401. """
  1402. # Import here to avoid circular import
  1403. from transformers.models import auto as auto_module
  1404. example_docstring = ""
  1405. # Use existing example section if available
  1406. if func_documentation is not None and (match := re.search(r"(?m)^([ \t]*)(?=Example)", func_documentation)):
  1407. example_docstring = func_documentation[match.start() :]
  1408. example_docstring = "\n" + set_min_indent(example_docstring, indent_level + 4)
  1409. # No examples for __init__ methods or if the class is not a model
  1410. elif parent_class is None and model_name_lowercase is not None:
  1411. task = rf"({'|'.join(PT_SAMPLE_DOCSTRINGS.keys())})"
  1412. model_task = re.search(task, class_name)
  1413. CONFIG_MAPPING = auto_module.configuration_auto.CONFIG_MAPPING
  1414. # Get checkpoint example
  1415. if (checkpoint_example := checkpoint) is None:
  1416. try:
  1417. checkpoint_example = get_checkpoint_from_config_class(CONFIG_MAPPING[model_name_lowercase])
  1418. except KeyError:
  1419. # For models with inconsistent lowercase model name
  1420. if model_name_lowercase in HARDCODED_CONFIG_FOR_MODELS:
  1421. CONFIG_MAPPING_NAMES = auto_module.configuration_auto.CONFIG_MAPPING_NAMES
  1422. config_class_name = HARDCODED_CONFIG_FOR_MODELS[model_name_lowercase]
  1423. if config_class_name in CONFIG_MAPPING_NAMES.values():
  1424. model_name_for_auto_config = [
  1425. k for k, v in CONFIG_MAPPING_NAMES.items() if v == config_class_name
  1426. ][0]
  1427. if model_name_for_auto_config in CONFIG_MAPPING:
  1428. checkpoint_example = get_checkpoint_from_config_class(
  1429. CONFIG_MAPPING[model_name_for_auto_config]
  1430. )
  1431. # Add example based on model task
  1432. if model_task is not None:
  1433. if checkpoint_example is not None:
  1434. example_annotation = ""
  1435. task = model_task.group()
  1436. example_annotation = PT_SAMPLE_DOCSTRINGS[task].format(
  1437. model_class=class_name,
  1438. checkpoint=checkpoint_example,
  1439. expected_output="...",
  1440. expected_loss="...",
  1441. qa_target_start_index=14,
  1442. qa_target_end_index=15,
  1443. mask="<mask>",
  1444. )
  1445. example_docstring = set_min_indent(example_annotation, indent_level + 4)
  1446. else:
  1447. print(
  1448. f"🚨 No checkpoint found for {class_name}.{func.__name__}. Please add a `checkpoint` arg to `auto_docstring` or add one in {config_class}'s docstring"
  1449. )
  1450. else:
  1451. # Check if the model is in a pipeline to get an example
  1452. for name_model_list_for_task in MODELS_TO_PIPELINE:
  1453. model_list_for_task = getattr(auto_module.modeling_auto, name_model_list_for_task)
  1454. if class_name in model_list_for_task.values():
  1455. pipeline_name = MODELS_TO_PIPELINE[name_model_list_for_task]
  1456. example_annotation = PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS[pipeline_name].format(
  1457. model_class=class_name,
  1458. checkpoint=checkpoint_example,
  1459. expected_output="...",
  1460. expected_loss="...",
  1461. qa_target_start_index=14,
  1462. qa_target_end_index=15,
  1463. )
  1464. example_docstring = set_min_indent(example_annotation, indent_level + 4)
  1465. break
  1466. return example_docstring
  1467. def auto_method_docstring(
  1468. func, parent_class=None, custom_intro=None, custom_args=None, checkpoint=None, source_args_dict=None
  1469. ):
  1470. """
  1471. Wrapper that automatically generates docstring.
  1472. """
  1473. # Use inspect to retrieve the method's signature
  1474. sig = inspect.signature(func)
  1475. indent_level = get_indent_level(func) if not parent_class else get_indent_level(parent_class)
  1476. # Get model information
  1477. model_name_lowercase, class_name, config_class = _get_model_info(func, parent_class)
  1478. func_documentation = func.__doc__
  1479. if custom_args is not None and func_documentation is not None:
  1480. func_documentation = set_min_indent(custom_args, indent_level + 4) + "\n" + func_documentation
  1481. elif custom_args is not None:
  1482. func_documentation = custom_args
  1483. # Add intro to the docstring before args description if needed
  1484. if custom_intro is not None:
  1485. docstring = set_min_indent(custom_intro, indent_level + 4)
  1486. if not docstring.strip().endswith("\n"):
  1487. docstring += "\n"
  1488. else:
  1489. docstring = add_intro_docstring(func, class_name=class_name, indent_level=indent_level)
  1490. # Process Parameters section
  1491. docstring += _process_parameters_section(
  1492. func_documentation, sig, func, class_name, model_name_lowercase, parent_class, indent_level, source_args_dict
  1493. )
  1494. # Process Returns section
  1495. return_docstring, func_documentation = _process_returns_section(
  1496. func_documentation, sig, config_class, indent_level
  1497. )
  1498. docstring += return_docstring
  1499. # Process Example section
  1500. example_docstring = _process_example_section(
  1501. func_documentation,
  1502. func,
  1503. parent_class,
  1504. class_name,
  1505. model_name_lowercase,
  1506. config_class,
  1507. checkpoint,
  1508. indent_level,
  1509. )
  1510. docstring += example_docstring
  1511. # Format the docstring with the placeholders
  1512. docstring = format_args_docstring(docstring, model_name_lowercase)
  1513. # Assign the dynamically generated docstring to the wrapper function
  1514. func.__doc__ = docstring
  1515. return func
  1516. def auto_class_docstring(cls, custom_intro=None, custom_args=None, checkpoint=None):
  1517. """
  1518. Wrapper that automatically generates a docstring for classes based on their attributes and methods.
  1519. """
  1520. # import here to avoid circular import
  1521. from transformers.models import auto as auto_module
  1522. is_dataclass = False
  1523. docstring_init = ""
  1524. docstring_args = ""
  1525. if "PreTrainedModel" in (x.__name__ for x in cls.__mro__):
  1526. docstring_init = auto_method_docstring(
  1527. cls.__init__, parent_class=cls, custom_args=custom_args, checkpoint=checkpoint
  1528. ).__doc__.replace("Args:", "Parameters:")
  1529. elif "ModelOutput" in (x.__name__ for x in cls.__mro__):
  1530. # We have a data class
  1531. is_dataclass = True
  1532. doc_class = cls.__doc__
  1533. if custom_args is None and doc_class:
  1534. custom_args = doc_class
  1535. docstring_args = auto_method_docstring(
  1536. cls.__init__,
  1537. parent_class=cls,
  1538. custom_args=custom_args,
  1539. checkpoint=checkpoint,
  1540. source_args_dict=get_args_doc_from_source(ModelOutputArgs),
  1541. ).__doc__
  1542. indent_level = get_indent_level(cls)
  1543. model_name_lowercase = get_model_name(cls)
  1544. model_name_title = " ".join([k.title() for k in model_name_lowercase.split("_")]) if model_name_lowercase else None
  1545. if model_name_lowercase and model_name_lowercase not in getattr(
  1546. getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]),
  1547. PLACEHOLDER_TO_AUTO_MODULE["config_class"][1],
  1548. ):
  1549. model_name_lowercase = model_name_lowercase.replace("_", "-")
  1550. name = re.findall(rf"({'|'.join(ClassDocstring.__dict__.keys())})$", cls.__name__)
  1551. if name == [] and custom_intro is None and not is_dataclass:
  1552. raise ValueError(
  1553. f"`{cls.__name__}` is not registered in the auto doc. Here are the available classes: {ClassDocstring.__dict__.keys()}.\n"
  1554. "Add a `custom_intro` to the decorator if you want to use `auto_docstring` on a class not registered in the auto doc."
  1555. )
  1556. if name != [] or custom_intro is not None or is_dataclass:
  1557. name = name[0] if name else None
  1558. if custom_intro is not None:
  1559. pre_block = equalize_indent(custom_intro, indent_level)
  1560. if not pre_block.endswith("\n"):
  1561. pre_block += "\n"
  1562. elif model_name_title is None or name is None:
  1563. pre_block = ""
  1564. else:
  1565. pre_block = getattr(ClassDocstring, name).format(model_name=model_name_title)
  1566. # Start building the docstring
  1567. docstring = set_min_indent(f"{pre_block}", indent_level) if len(pre_block) else ""
  1568. if name != "PreTrainedModel" and "PreTrainedModel" in (x.__name__ for x in cls.__mro__):
  1569. docstring += set_min_indent(f"{ClassDocstring.PreTrainedModel}", indent_level)
  1570. # Add the __init__ docstring
  1571. if docstring_init:
  1572. docstring += set_min_indent(f"\n{docstring_init}", indent_level)
  1573. elif is_dataclass:
  1574. # No init function, we have a data class
  1575. docstring += docstring_args if docstring_args else "\nArgs:\n"
  1576. source_args_dict = get_args_doc_from_source(ModelOutputArgs)
  1577. doc_class = cls.__doc__ if cls.__doc__ else ""
  1578. documented_kwargs = parse_docstring(doc_class)[0]
  1579. for param_name, param_type_annotation in cls.__annotations__.items():
  1580. param_type = str(param_type_annotation)
  1581. optional = False
  1582. # Process parameter type
  1583. if "typing" in param_type:
  1584. param_type = "".join(param_type.split("typing.")).replace("transformers.", "~")
  1585. else:
  1586. param_type = f"{param_type.replace('transformers.', '~').replace('builtins', '')}.{param_name}"
  1587. if "ForwardRef" in param_type:
  1588. param_type = re.sub(r"ForwardRef\('([\w.]+)'\)", r"\1", param_type)
  1589. if "Optional" in param_type:
  1590. param_type = re.sub(r"Optional\[(.*?)\]", r"\1", param_type)
  1591. optional = True
  1592. # Check for default value
  1593. param_default = ""
  1594. param_default = str(getattr(cls, param_name, ""))
  1595. param_default = f", defaults to `{param_default}`" if param_default != "" else ""
  1596. param_type, optional_string, shape_string, additional_info, description, is_documented = (
  1597. _get_parameter_info(param_name, documented_kwargs, source_args_dict, param_type, optional)
  1598. )
  1599. if is_documented:
  1600. # Check if type is missing
  1601. if param_type == "":
  1602. print(f"🚨 {param_name} for {cls.__qualname__} in file {cls.__code__.co_filename} has no type")
  1603. param_type = param_type if "`" in param_type else f"`{param_type}`"
  1604. # Format the parameter docstring
  1605. if additional_info:
  1606. docstring += set_min_indent(
  1607. f"{param_name} ({param_type}{additional_info}):{description}",
  1608. indent_level + 8,
  1609. )
  1610. else:
  1611. docstring += set_min_indent(
  1612. f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}",
  1613. indent_level + 8,
  1614. )
  1615. # TODO (Yoni): Add support for Attributes section in docs
  1616. else:
  1617. print(
  1618. f"You used `@auto_class_docstring` decorator on `{cls.__name__}` but this class is not part of the AutoMappings. Remove the decorator"
  1619. )
  1620. # Assign the dynamically generated docstring to the wrapper class
  1621. cls.__doc__ = docstring
  1622. return cls
  1623. def auto_docstring(obj=None, *, custom_intro=None, custom_args=None, checkpoint=None):
  1624. r"""
  1625. Automatically generates comprehensive docstrings for model classes and methods in the Transformers library.
  1626. This decorator reduces boilerplate by automatically including standard argument descriptions while allowing
  1627. overrides to add new or custom arguments. It inspects function signatures, retrieves predefined docstrings
  1628. for common arguments (like `input_ids`, `attention_mask`, etc.), and generates complete documentation
  1629. including examples and return value descriptions.
  1630. For complete documentation and examples, read this [guide](https://huggingface.co/docs/transformers/auto_docstring).
  1631. Examples of usage:
  1632. Basic usage (no parameters):
  1633. ```python
  1634. @auto_docstring
  1635. class MyAwesomeModel(PreTrainedModel):
  1636. def __init__(self, config, custom_parameter: int = 10):
  1637. r'''
  1638. custom_parameter (`int`, *optional*, defaults to 10):
  1639. Description of the custom parameter for MyAwesomeModel.
  1640. '''
  1641. super().__init__(config)
  1642. self.custom_parameter = custom_parameter
  1643. ```
  1644. Using `custom_intro` with a class:
  1645. ```python
  1646. @auto_docstring(
  1647. custom_intro="This model implements a novel attention mechanism for improved performance."
  1648. )
  1649. class MySpecialModel(PreTrainedModel):
  1650. def __init__(self, config, attention_type: str = "standard"):
  1651. r'''
  1652. attention_type (`str`, *optional*, defaults to "standard"):
  1653. Type of attention mechanism to use.
  1654. '''
  1655. super().__init__(config)
  1656. ```
  1657. Using `custom_intro` with a method, and specify custom arguments and example directly in the docstring:
  1658. ```python
  1659. @auto_docstring(
  1660. custom_intro="Performs forward pass with enhanced attention computation."
  1661. )
  1662. def forward(
  1663. self,
  1664. input_ids: Optional[torch.Tensor] = None,
  1665. attention_mask: Optional[torch.Tensor] = None,
  1666. ):
  1667. r'''
  1668. custom_parameter (`int`, *optional*, defaults to 10):
  1669. Description of the custom parameter for MyAwesomeModel.
  1670. Example:
  1671. ```python
  1672. >>> model = MyAwesomeModel(config)
  1673. >>> model.forward(input_ids=torch.tensor([1, 2, 3]), attention_mask=torch.tensor([1, 1, 1]))
  1674. ```
  1675. '''
  1676. ```
  1677. Using `custom_args` to define reusable arguments:
  1678. ```python
  1679. VISION_ARGS = r'''
  1680. pixel_values (`torch.FloatTensor`, *optional*):
  1681. Pixel values of the input images.
  1682. image_features (`torch.FloatTensor`, *optional*):
  1683. Pre-computed image features for efficient processing.
  1684. '''
  1685. @auto_docstring(custom_args=VISION_ARGS)
  1686. def encode_images(self, pixel_values=None, image_features=None):
  1687. # ... method implementation
  1688. ```
  1689. Combining `custom_intro` and `custom_args`:
  1690. ```python
  1691. MULTIMODAL_ARGS = r'''
  1692. vision_features (`torch.FloatTensor`, *optional*):
  1693. Pre-extracted vision features from the vision encoder.
  1694. fusion_strategy (`str`, *optional*, defaults to "concat"):
  1695. Strategy for fusing text and vision modalities.
  1696. '''
  1697. @auto_docstring(
  1698. custom_intro="Processes multimodal inputs combining text and vision.",
  1699. custom_args=MULTIMODAL_ARGS
  1700. )
  1701. def forward(
  1702. self,
  1703. input_ids,
  1704. attention_mask=None,
  1705. vision_features=None,
  1706. fusion_strategy="concat"
  1707. ):
  1708. # ... multimodal processing
  1709. ```
  1710. Using with ModelOutput classes:
  1711. ```python
  1712. @dataclass
  1713. @auto_docstring(
  1714. custom_intro="Custom model outputs with additional fields."
  1715. )
  1716. class MyModelOutput(ImageClassifierOutput):
  1717. r'''
  1718. loss (`torch.FloatTensor`, *optional*):
  1719. The loss of the model.
  1720. custom_field (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
  1721. A custom output field specific to this model.
  1722. '''
  1723. # Standard fields like hidden_states, logits, attentions etc. can be automatically documented
  1724. # However, given that the loss docstring is often different per model, you should document it above
  1725. loss: Optional[torch.FloatTensor] = None
  1726. logits: Optional[torch.FloatTensor] = None
  1727. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  1728. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  1729. custom_field: Optional[torch.FloatTensor] = None
  1730. ```
  1731. Args:
  1732. custom_intro (`str`, *optional*):
  1733. Custom introduction text to add to the docstring. This replaces the default
  1734. introduction text generated by the decorator before the Args section. Use this to describe what
  1735. makes your model or method special.
  1736. custom_args (`str`, *optional*):
  1737. Custom argument documentation in docstring format. This allows you to define
  1738. argument descriptions once and reuse them across multiple methods. The format should follow the
  1739. standard docstring convention: `arg_name (`type`, *optional*, defaults to `value`): Description.`
  1740. checkpoint (`str`, *optional*):
  1741. Checkpoint name to use in examples within the docstring. This is typically
  1742. automatically inferred from the model configuration class, but can be overridden if needed for
  1743. custom examples.
  1744. Note:
  1745. - Standard arguments (`input_ids`, `attention_mask`, `pixel_values`, etc.) are automatically documented
  1746. from predefined descriptions and should not be redefined unless their behavior differs in your model.
  1747. - New or custom arguments should be documented in the method's docstring using the `r''' '''` block
  1748. or passed via the `custom_args` parameter.
  1749. - For model classes, the decorator derives parameter descriptions from the `__init__` method's signature
  1750. and docstring.
  1751. - Return value documentation is automatically generated for methods that return ModelOutput subclasses.
  1752. """
  1753. def auto_docstring_decorator(obj):
  1754. if len(obj.__qualname__.split(".")) > 1:
  1755. return auto_method_docstring(
  1756. obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint
  1757. )
  1758. else:
  1759. return auto_class_docstring(obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint)
  1760. if obj:
  1761. return auto_docstring_decorator(obj)
  1762. return auto_docstring_decorator