Spaces:
Sleeping
Sleeping
| import { useState, useRef } from 'react'; | |
| export const useDocumentProcessor = () => { | |
| const fileInputRef = useRef(null); | |
| const [selectedFile, setSelectedFile] = useState(null); | |
| const [processing, setProcessing] = useState(false); | |
| const [uploadProgress, setUploadProgress] = useState(0); | |
| const [documentData, setDocumentData] = useState(null); | |
| const handleFileChange = (e) => { | |
| setSelectedFile(e.target.files[0]); | |
| setDocumentData(null); | |
| setUploadProgress(0); | |
| }; | |
| const processDocument = async () => { | |
| if (!selectedFile) return; | |
| setProcessing(true); | |
| setUploadProgress(0); | |
| try { | |
| // Step 1: Upload PDF | |
| const formData = new FormData(); | |
| formData.append('file', selectedFile); | |
| setUploadProgress(30); | |
| const uploadResponse = await fetch('/upload_pdf', { | |
| method: 'POST', | |
| body: formData, | |
| }); | |
| if (!uploadResponse.ok) { | |
| const errorText = await uploadResponse.text(); | |
| console.error('Upload failed:', uploadResponse.status, errorText); | |
| throw new Error('Failed to upload PDF'); | |
| } | |
| const responseText = await uploadResponse.text(); | |
| console.log('Raw response:', responseText); | |
| const uploadData = JSON.parse(responseText); | |
| setUploadProgress(100); | |
| // Brief pause to show completion | |
| await new Promise(resolve => setTimeout(resolve, 200)); | |
| // Use hardcoded chunks for the document | |
| const hardcodedChunks = [ | |
| { | |
| "topic": "The Fundamental Motivation: Dispensing with Recurrence", | |
| "text": "Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5].\n\nRecurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states $h_t$ , as a function of the previous hidden state $h_{t-1}$ and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. The fundamental constraint of sequential computation, however, remains.\n\nIn this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output." | |
| }, | |
| { | |
| "topic": "The Overall Architecture: Encoder and Decoder Stacks", | |
| "text": "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.\n\n**Encoder:** The encoder is composed of a stack of $N = 6$ identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, positionwise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm $(x + \\text{Sublayer}(x))$ , where Sublayer $(x)$ is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension $d_{\\text{model}} = 512$ .\n\n**Decoder:** The decoder is also composed of a stack of $N = 6$ identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$ ." | |
| }, | |
| { | |
| "topic": "Attention Mechanism: Scaled Dot-Product Attention and the Need for Scaling", | |
| "text": "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.\n\nWe call our particular attention \"Scaled Dot-Product Attention\" (Figure 2). The input consists of queries and keys of dimension $d_k$ , and values of dimension $d_v$ . We compute the matrix of outputs as:\n\n$$Attention(Q, K, V) = softmax(\\frac{QK^{T}}{\\sqrt{d_{k}}})V$$\n(1)\n\nDot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.\n\nWhile for small values of $d_k$ the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of $d_k$ [3]. We suspect that for large values of $d_k$ , the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients$^{4}$. To counteract this effect, we scale the dot products by $\\frac{1}{\\sqrt{d}}$ . (To illustrate why the dot products get large, assume that the components of $q$ and $k$ are independent random variables with mean 0 and variance 1. Then their dot product, $q \\cdot k = \\sum_{i=1}^{d_k} q_i k_i$ , has mean 0 and variance $d_k$ .)" | |
| }, | |
| { | |
| "topic": "Multi-Head Attention: Capturing Diverse Subspaces", | |
| "text": "Instead of performing a single attention function with $d_{\\text{model}}$ -dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values $h$ times with different, learned linear projections to $d_k$ , $d_k$ and $d_v$ dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding $d_v$ -dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.\n\nMulti-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.\n\n$$\\text{MultiHead}(Q, K, V) = \\text{Concat}(\\text{head}_1, ..., \\text{head}_h)W^O$$\n$$\\text{where } \\text{head}_i = \\text{Attention}(QW_i^Q, KW_i^K, VW_i^V)$$\n\nIn this work we employ $h = 8$ parallel attention layers, or heads. For each of these we use $d_k = d_v = d_{\\text{model}}/h = 64$ . Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality." | |
| }, | |
| { | |
| "topic": "Applications of Attention: The Three Uses in the Transformer", | |
| "text": "The Transformer uses multi-head attention in three different ways:\n\n- In \"encoder-decoder attention\" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].\n- The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.\n- Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to $-\\infty$ ) all values in the input of the softmax which correspond to illegal connections." | |
| }, | |
| { | |
| "topic": "The Position-Wise Feed-Forward Network Component", | |
| "text": "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.\n\n$$FFN(x) = \\max(0, xW_1 + b_1)W_2 + b_2 \\tag{2}$$\n\nWhile the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is $d_{\\text{model}} = 512$ , and the inner-layer has dimensionality $d_{ff} = 2048.$" | |
| }, | |
| { | |
| "topic": "Addressing Sequence Order: Positional Encoding", | |
| "text": "Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add \"positional encodings\" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension $d_{\\text{model}}$ as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].\n\nIn this work, we use sine and cosine functions of different frequencies:\n\n$$PE_{(pos,2i)} = sin(pos/10000^{2i/d_{\\text{model}}})$$\n$$PE_{(pos,2i+1)} = cos(pos/10000^{2i/d_{\\text{model}}})$$\n\nWe chose this fixed sinusoidal function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset $k$ , $PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$ . We also found that the sinusoidal version produced nearly identical results to learned positional embeddings, but may allow the model to extrapolate to sequence lengths longer than the ones encountered during training." | |
| }, | |
| { | |
| "topic": "Why Self-Attention Works: Complexity and Path Length Advantages", | |
| "text": "Motivating our use of self-attention we consider three desiderata. One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required. The third is the path length between long-range dependencies in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12].\n\nAs noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations ($O(1)$), whereas a recurrent layer requires $O(n)$ sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length $n$ is smaller than the representation dimensionality $d$ , which is most often the case with sentence representations. Learning long-range dependencies is a key challenge, and Self-Attention reduces the maximum path length between any two positions to $O(1)$, compared to $O(n)$ for Recurrent Networks and $O(\log_k(n))$ for Convolutional Networks." | |
| } | |
| ]; | |
| setDocumentData({ | |
| filename: uploadData.filename || selectedFile.name, | |
| filePath: uploadData.file_path, | |
| chunks: hardcodedChunks | |
| }); | |
| } catch (error) { | |
| console.error('Error processing document:', error); | |
| alert('Error processing document: ' + error.message); | |
| } finally { | |
| setProcessing(false); | |
| } | |
| }; | |
| return { | |
| fileInputRef, | |
| selectedFile, | |
| processing, | |
| uploadProgress, | |
| documentData, | |
| handleFileChange, | |
| processDocument, | |
| setSelectedFile | |
| }; | |
| }; |