File size: 4,814 Bytes
4289090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import json
import re
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
import torch
import warnings
import spaces

flash_attn_installed = False
try:
    import subprocess
    print("Installing flash-attn...")
    subprocess.run(
    "pip install flash-attn --no-build-isolation",
    env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
    shell=True,
    )
    flash_attn_installed = True
except Exception as e:
    print(f"Error installing flash-attn: {e}")


# Suppress specific warnings
warnings.filterwarnings(
    "ignore",
    message="You have modified the pretrained model configuration to control generation.",
)
warnings.filterwarnings(
    "ignore",
    message="You are not running the flash-attention implementation, expect numerical differences.",
)

print("Initializing application...")

model = AutoModelForCausalLM.from_pretrained(
    "sciphi/triplex", 
    trust_remote_code=True,
    attn_implementation="flash_attention_2" if flash_attn_installed else None,
    torch_dtype=torch.bfloat16,
    device_map="auto", 
    low_cpu_mem_usage=True,#advised if any device map given
).eval()

tokenizer = AutoTokenizer.from_pretrained(
    "sciphi/triplex", 
    trust_remote_code=True,
    attn_implementation="flash_attention_2",
        torch_dtype=torch.bfloat16,
    )


print("Model and tokenizer loaded successfully.")

# Set up generation config
generation_config = GenerationConfig.from_pretrained("sciphi/triplex")
generation_config.max_length = 2048
generation_config.pad_token_id = tokenizer.eos_token_id
@spaces.GPU
def triplextract(text, entity_types, predicates):
    input_format = """Perform Named Entity Recognition (NER) and extract knowledge graph triplets from the text. NER identifies named entities of given entity types, and triple extraction identifies relationships between entities using specified predicates. Return the result as a JSON object with an "entities_and_triples" key containing an array of entities and triples.
        **Entity Types:**
        {entity_types}
        **Predicates:**
        {predicates}
        **Text:**
        {text}
        """
    message = input_format.format(
                entity_types = json.dumps({"entity_types": entity_types}),
                predicates = json.dumps({"predicates": predicates}),
                text = text)
    
    # message = input_format.format(
    #     entity_types=entity_types, predicates=predicates, text=text
    # )

    messages = [{"role": "user", "content": message}]

    print("Tokenizing input...")
    input_ids = tokenizer.apply_chat_template(
        messages, add_generation_prompt=True, return_tensors="pt"
    ).to(model.device)

    attention_mask = input_ids.ne(tokenizer.pad_token_id)

    print("Generating output...")
    try:
        with torch.no_grad():
            output = model.generate(
                input_ids=input_ids,
                attention_mask=attention_mask,
                generation_config=generation_config,
                do_sample=True,
            )

        decoded_output = tokenizer.decode(output[0], skip_special_tokens=True)
        print("Decoding output completed.")

        return decoded_output
    except torch.cuda.OutOfMemoryError as e:
        print(f"CUDA out of memory error: {e}")
        return "Error: CUDA out of memory."
    except Exception as e:
        print(f"Error in generation: {e}")
        return f"Error in generation: {str(e)}"

def parse_triples(prediction):
    entities = {}
    relationships = []

    try:
        data = json.loads(prediction)
        items = data.get("entities_and_triples", [])
    except json.JSONDecodeError:
        json_match = re.search(r"```json\s*(.*?)\s*```", prediction, re.DOTALL)
        if json_match:
            try:
                data = json.loads(json_match.group(1))
                items = data.get("entities_and_triples", [])
            except json.JSONDecodeError:
                items = re.findall(r"\[(.*?)\]", prediction)
        else:
            items = re.findall(r"\[(.*?)\]", prediction)

    for item in items:
        if isinstance(item, str):
            if ":" in item:
                id, entity = item.split(",", 1)
                id = id.strip("[]").strip()
                entity_type, entity_value = entity.split(":", 1)
                entities[id] = {
                    "type": entity_type.strip(),
                    "value": entity_value.strip(),
                }
            else:
                parts = item.split()
                if len(parts) >= 3:
                    source = parts[0].strip("[]")
                    relation = " ".join(parts[1:-1])
                    target = parts[-1].strip("[]")
                    relationships.append((source, relation.strip(), target))

    return entities, relationships