# Graphormer[[graphormer]]

이 모델은 유지 보수 모드로만 운영되며, 코드를 변경하는 새로운 PR(Pull Request)은 받지 않습니다.
이 모델을 실행하는 데 문제가 발생한다면, 이 모델을 지원하는 마지막 버전인 v4.40.2를 다시 설치해 주세요. 다음 명령어를 실행하여 재설치할 수 있습니다: `pip install -U transformers==4.40.2`.

## 개요[[overview]]

Graphormer 모델은 Chengxuan Ying, Tianle Cai, Shengjie Luo, Shuxin Zheng, Guolin Ke, Di He, Yanming Shen, Tie-Yan Liu가 제안한 [트랜스포머가 그래프 표현에 있어서 정말 약할까?](https://huggingface.co/papers/2106.05234) 라는 논문에서 소개되었습니다. Graphormer는 그래프 트랜스포머 모델입니다. 텍스트 시퀀스 대신 그래프에서 계산을 수행할 수 있도록 수정되었으며, 전처리와 병합 과정에서 임베딩과 관심 특성을 생성한 후 수정된 어텐션을 사용합니다.

해당 논문의 초록입니다:

*트랜스포머 아키텍처는 자연어 처리와 컴퓨터 비전 등 많은 분야에서 지배적인 선택을 받고 있는 아키텍처 입니다. 그러나 그래프 수준 예측 리더보드 상에서는 주류 GNN 변형모델들에 비해 경쟁력 있는 성능을 달성하지 못했습니다. 따라서 트랜스포머가 그래프 표현 학습에서 어떻게 잘 수행될 수 있을지는 여전히 미스터리였습니다. 본 논문에서는 Graphormer를 제시함으로써 이 미스터리를 해결합니다. Graphormer는 표준 트랜스포머 아키텍처를 기반으로 구축되었으며, 특히 최근의 OpenGraphBenchmark Large-Scale Challenge(OGB-LSC)의 광범위한 그래프 표현 학습 작업에서 탁월한 결과를 얻을 수 있었습니다. 그래프에서 트랜스포머를 활용하는데 핵심은 그래프의 구조적 정보를 모델에 효과적으로 인코딩하는 것입니다. 이를 위해 우리는 Graphormer가 그래프 구조 데이터를 더 잘 모델링할 수 있도록 돕는 몇 가지 간단하면서도 효과적인 구조적 인코딩 방법을 제안합니다. 또한, 우리는 Graphormer의 표현을 수학적으로 특성화하고, 그래프의 구조적 정보를 인코딩하는 우리의 방식으로 많은 인기 있는 GNN 변형모델들이 Graphormer의 특수한 경우로 포함될 수 있음을 보여줍니다.*

이 모델은 [clefourrier](https://huggingface.co/clefourrier)가 기여했습니다. 원본 코드는 [이곳](https://github.com/microsoft/Graphormer)에서 확인할 수 있습니다.

## 사용 팁[[usage-tips]]

이 모델은 큰 그래프(100개 이상의 노드개수/엣지개수)에서는 메모리 사용량이 폭발적으로 증가하므로 잘 작동하지 않습니다. 대안으로 배치 크기를 줄이거나, RAM을 늘리거나 또는 algos_graphormer.pyx 파일의 `UNREACHABLE_NODE_DISTANCE` 매개변수를 줄이는 방법도 있지만, 700개 이상의 노드개수/엣지개수를 처리하기에는 여전히 어려울 것입니다.

이 모델은 토크나이저를 사용하지 않고, 대신 훈련 중에 특별한 콜레이터(collator)를 사용합니다.

## GraphormerConfig[[transformers.GraphormerConfig]][[transformers.GraphormerConfig]]

#### transformers.GraphormerConfig[[transformers.GraphormerConfig]]

[Source](https://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/models/deprecated/graphormer/configuration_graphormer.py#L26)

This is the configuration class to store the configuration of a [~GraphormerModel](/docs/transformers/v4.57.1/ko/model_doc/graphormer#transformers.GraphormerModel). It is used to instantiate an
Graphormer 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 Graphormer
[graphormer-base-pcqm4mv1](https://huggingface.co/graphormer-base-pcqm4mv1) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.57.1/ko/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/v4.57.1/ko/main_classes/configuration#transformers.PretrainedConfig) for more information.

**Parameters:**

num_classes (`int`, *optional*, defaults to 1) : Number of target classes or labels, set to n for binary classification of n tasks.

num_atoms (`int`, *optional*, defaults to 512*9) : Number of node types in the graphs.

num_edges (`int`, *optional*, defaults to 512*3) : Number of edges types in the graph.

num_in_degree (`int`, *optional*, defaults to 512) : Number of in degrees types in the input graphs.

num_out_degree (`int`, *optional*, defaults to 512) : Number of out degrees types in the input graphs.

num_edge_dis (`int`, *optional*, defaults to 128) : Number of edge dis in the input graphs.

multi_hop_max_dist (`int`, *optional*, defaults to 20) : Maximum distance of multi hop edges between two nodes.

spatial_pos_max (`int`, *optional*, defaults to 1024) : Maximum distance between nodes in the graph attention bias matrices, used during preprocessing and collation.

edge_type (`str`, *optional*, defaults to multihop) : Type of edge relation chosen.

max_nodes (`int`, *optional*, defaults to 512) : Maximum number of nodes which can be parsed for the input graphs.

share_input_output_embed (`bool`, *optional*, defaults to `False`) : Shares the embedding layer between encoder and decoder - careful, True is not implemented.

num_layers (`int`, *optional*, defaults to 12) : Number of layers.

embedding_dim (`int`, *optional*, defaults to 768) : Dimension of the embedding layer in encoder.

ffn_embedding_dim (`int`, *optional*, defaults to 768) : Dimension of the "intermediate" (often named feed-forward) layer in encoder.

num_attention_heads (`int`, *optional*, defaults to 32) : Number of attention heads in the encoder.

self_attention (`bool`, *optional*, defaults to `True`) : Model is self attentive (False not implemented).

activation_function (`str` or `function`, *optional*, defaults to `"gelu"`) : The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported.

dropout (`float`, *optional*, defaults to 0.1) : The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.

attention_dropout (`float`, *optional*, defaults to 0.1) : The dropout probability for the attention weights.

activation_dropout (`float`, *optional*, defaults to 0.1) : The dropout probability for the activation of the linear transformer layer.

layerdrop (`float`, *optional*, defaults to 0.0) : The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more details.

bias (`bool`, *optional*, defaults to `True`) : Uses bias in the attention module - unsupported at the moment.

embed_scale(`float`, *optional*, defaults to None) : Scaling factor for the node embeddings.

num_trans_layers_to_freeze (`int`, *optional*, defaults to 0) : Number of transformer layers to freeze.

encoder_normalize_before (`bool`, *optional*, defaults to `False`) : Normalize features before encoding the graph.

pre_layernorm (`bool`, *optional*, defaults to `False`) : Apply layernorm before self attention and the feed forward network. Without this, post layernorm will be used.

apply_graphormer_init (`bool`, *optional*, defaults to `False`) : Apply a custom graphormer initialisation to the model before training.

freeze_embeddings (`bool`, *optional*, defaults to `False`) : Freeze the embedding layer, or train it along the model.

encoder_normalize_before (`bool`, *optional*, defaults to `False`) : Apply the layer norm before each encoder block.

q_noise (`float`, *optional*, defaults to 0.0) : Amount of quantization noise (see "Training with Quantization Noise for Extreme Model Compression"). (For more detail, see fairseq's documentation on quant_noise).

qn_block_size (`int`, *optional*, defaults to 8) : Size of the blocks for subsequent quantization with iPQ (see q_noise).

kdim (`int`, *optional*, defaults to None) : Dimension of the key in the attention, if different from the other values.

vdim (`int`, *optional*, defaults to None) : Dimension of the value in the attention, if different from the other values.

use_cache (`bool`, *optional*, defaults to `True`) : Whether or not the model should return the last key/values attentions (not used by all models).

traceable (`bool`, *optional*, defaults to `False`) : Changes return value of the encoder's inner_state to stacked tensors. 

Example : ```python >>> from transformers import GraphormerForGraphClassification, GraphormerConfig  >>> # Initializing a Graphormer graphormer-base-pcqm4mv2 style configuration >>> configuration = GraphormerConfig()  >>> # Initializing a model from the graphormer-base-pcqm4mv1 style configuration >>> model = GraphormerForGraphClassification(configuration)  >>> # Accessing the model configuration >>> configuration = model.config ```

## GraphormerModel[[transformers.GraphormerModel]][[transformers.GraphormerModel]]

#### transformers.GraphormerModel[[transformers.GraphormerModel]]

[Source](https://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/models/deprecated/graphormer/modeling_graphormer.py#L769)

The Graphormer model is a graph-encoder model.

It goes from a graph to its representation. If you want to use the model for a downstream classification task, use
GraphormerForGraphClassification instead. For any other downstream task, feel free to add a new class, or combine
this model with a downstream model of your choice, following the example in GraphormerForGraphClassification.

forwardtransformers.GraphormerModel.forwardhttps://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/models/deprecated/graphormer/modeling_graphormer.py#L798[{"name": "input_nodes", "val": ": LongTensor"}, {"name": "input_edges", "val": ": LongTensor"}, {"name": "attn_bias", "val": ": Tensor"}, {"name": "in_degree", "val": ": LongTensor"}, {"name": "out_degree", "val": ": LongTensor"}, {"name": "spatial_pos", "val": ": LongTensor"}, {"name": "attn_edge_type", "val": ": LongTensor"}, {"name": "perturb", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "masked_tokens", "val": ": None = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}, {"name": "**unused", "val": ""}]

## GraphormerForGraphClassification[[transformers.GraphormerForGraphClassification]][[transformers.GraphormerForGraphClassification]]

#### transformers.GraphormerForGraphClassification[[transformers.GraphormerForGraphClassification]]

[Source](https://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/models/deprecated/graphormer/modeling_graphormer.py#L840)

This model can be used for graph-level classification or regression tasks.

It can be trained on
- regression (by setting config.num_classes to 1); there should be one float-type label per graph
- one task classification (by setting config.num_classes to the number of classes); there should be one integer
  label per graph
- binary multi-task classification (by setting config.num_classes to the number of labels); there should be a list
  of integer labels for each graph.

forwardtransformers.GraphormerForGraphClassification.forwardhttps://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/models/deprecated/graphormer/modeling_graphormer.py#L863[{"name": "input_nodes", "val": ": LongTensor"}, {"name": "input_edges", "val": ": LongTensor"}, {"name": "attn_bias", "val": ": Tensor"}, {"name": "in_degree", "val": ": LongTensor"}, {"name": "out_degree", "val": ": LongTensor"}, {"name": "spatial_pos", "val": ": LongTensor"}, {"name": "attn_edge_type", "val": ": LongTensor"}, {"name": "labels", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}, {"name": "**unused", "val": ""}]

