Transformers documentation
SLANeXt
This model was contributed to Hugging Face Transformers on 2026-03-21.
SLANeXt
Overview
SLANeXt_wired and SLANeXt_wireless are part of a series of dedicated lightweight models for table structure recognition, focusing on accurately recognizing table structures in documents and natural scenes. For more details about the SLANeXt series model, please refer to the official documentation.
Model Architecture
The SLANeXt series is a new generation of table structure recognition models independently developed by the Baidu PaddlePaddle Vision Team. SLANeXt focuses on table structure recognition, and trains dedicated weights for wired and wireless tables separately. The recognition ability for all types of tables has been significantly improved, especially for wired tables.
Usage
Single input inference
The example below demonstrates how to detect text with PP-OCRV5_Mobile_Det using the AutoModel.
import requests
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForTableRecognition
model_path="PaddlePaddle/SLANeXt_wired_safetensors"
model = AutoModelForTableRecognition.from_pretrained(model_path, device_map="auto")
image_processor = AutoImageProcessor.from_pretrained(model_path)
image = Image.open(requests.get("https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/table_recognition.jpg", stream=True).raw)
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
outputs = model(**inputs)
results = image_processor.post_process_table_recognition(outputs)
print(result['structure'])
print(result['structure_score'])SLANeXtConfig
class transformers.SLANeXtConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Nonevision_config: dict | transformers.models.slanext.configuration_slanext.SLANeXtVisionConfig | None = Nonepost_conv_in_channels: int = 256post_conv_out_channels: int = 512out_channels: int = 50hidden_size: int = 512max_text_length: int = 500 )
Parameters
- vision_config (
dictorSLANeXtVisionConfig, optional) — Configuration for the vision encoder. IfNone, a defaultSLANeXtVisionConfigis used. - post_conv_in_channels (
int, optional, defaults to 256) — Number of input channels for the post-encoder convolution layer. - post_conv_out_channels (
int, optional, defaults to 512) — Number of output channels for the post-encoder convolution layer. - out_channels (
int, optional, defaults to 50) — Vocabulary size for the table structure token prediction head, i.e., the number of distinct structure tokens the model can predict. - hidden_size (
int, optional, defaults to 512) — Dimensionality of the hidden states in the attention GRU cell and the structure/location prediction heads. - max_text_length (
int, optional, defaults to 500) — Maximum number of autoregressive decoding steps (tokens) for the structure and location decoder.
This is the configuration class to store the configuration of a SlanextModel. It is used to instantiate a Slanext model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the PaddlePaddle/SLANeXt_wired_safetensors
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
SLANeXtForTableRecognition
class transformers.SLANeXtForTableRecognition
< source >( config: SLANeXtConfig )
Parameters
- config (SLANeXtConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
SLANeXt Table Recognition model for table recognition tasks. Wraps the core SLANeXtPreTrainedModel and returns outputs compatible with the Transformers table recognition API.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( pixel_values: FloatTensor**kwargs: Unpack ) → SLANeXtForTableRecognitionOutput or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size)) — The tensors corresponding to the input images. Pixel values can be obtained using SLANeXtImageProcessor. SeeSLANeXtImageProcessor.__call__()for details (processor_classuses SLANeXtImageProcessor for processing images).
Returns
SLANeXtForTableRecognitionOutput or tuple(torch.FloatTensor)
A SLANeXtForTableRecognitionOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (SLANeXtConfig) and inputs.
The SLANeXtForTableRecognition forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
head_hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Hidden-states of the SLANeXtSLAHead at each prediction step, varies up to maxself.config.max_text_lengthstates (depending on early exits).head_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Attentions of the SLANeXtSLAHead at each prediction step, varies up to maxself.config.max_text_lengthattentions (depending on early exits).
SLANeXtBackbone
SLANeXtSLAHead
SLANeXtImageProcessor
class transformers.SLANeXtImageProcessor
< source >( **kwargs: Unpack )
Parameters
- do_convert_rgb (
bool, kwargs, optional, defaults toTrue) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional, defaults toTrue) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 512, 'width': 512}): Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional, defaults toTrue) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, defaults to2) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional, defaults toTrue) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional, defaults to0.00392156862745098) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional, defaults toTrue) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.485, 0.456, 0.406]) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.229, 0.224, 0.225]) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional, defaults toTrue) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 512, 'width': 512}): The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:"channels_first"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models.
Constructs a SLANeXtImageProcessor image processor.
Initialize the decoder vocabulary for table structure recognition.
Builds a character dictionary mapping HTML table structure tokens (e.g., <thead>, <tr>, <td>, colspan/
rowspan attributes) to integer indices. The dictionary includes special "sos" (start-of-sequence) and "eos" (end-of-sequence) tokens. Merged <td></td> tokens are used in place of standalone <td> tokens
when applicable.
post_process_table_recognition
< source >( outputs ) → dict
Parameters
- outputs (
SLANeXtForTableRecognitionOutput) — Raw outputs from the SLANeXt model. Thelast_hidden_statefield contains the predicted probability distributions over the structure vocabulary at each decoding step, with shape(batch_size, max_text_length, num_classes).
Returns
dict
A dictionary containing:
- structure (
list[str]): The predicted HTML table structure as a list of tokens, wrapped with<html>,<body>, and<table>tags. - structure_score (
float): The mean confidence score across all predicted tokens.
Post-process the raw model outputs to decode the predicted table structure into an HTML token sequence.
Converts the model’s predicted probability distributions over the structure vocabulary into a sequence of
HTML tokens representing the table structure. The decoded tokens are wrapped with <html>, <body>, and <table> tags to form a complete HTML table structure.