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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import dataclasses
import pprint
from functools import partial
import re
import os
from threading import Lock
import urllib
import time
from typing import List, Optional, Union

from pydantic import BaseModel
import absl.logging
from tqdm import tqdm, trange
import numpy as np
import mlxu
from ml_collections import ConfigDict
import uvicorn
from fastapi import FastAPI
import gradio as gr
import requests
from requests.exceptions import Timeout, ConnectionError


class InferenceRequest(BaseModel):
    prefix_text: Optional[List[str]] = None
    text: Optional[List[str]] = None
    until: Optional[Union[List[str], List[List[str]]]] = None
    temperature: Optional[float] = None


class ChatRequest(BaseModel):
    prompt: str
    context: str = ''
    temperature: Optional[float] = None


class LMServer(object):
    """ HTTP server for serving langauge models. """

    @staticmethod
    def get_default_config(updates=None):
        config = ConfigDict()
        config.host = '0.0.0.0'
        config.port = 5007
        config.batch_size = 1
        config.logging = False
        config.pre_compile = 'loglikelihood'
        config.default_temperature = 1.0
        config.greedy_until_max_length = 5000
        config.prepend_to_prefix = ''
        config.append_to_prefix = ''
        config.prepend_to_text = ''
        config.append_to_text = ''
        config.chat_prepend_text = ''
        config.chat_user_prefix = ''
        config.chat_user_suffix = ''
        config.chat_lm_prefix = ''
        config.chat_lm_suffix = ''
        config.notes = ''

        if updates is not None:
            config.update(ConfigDict(updates).copy_and_resolve_references())
        return config

    def __init__(self, config):
        self.config = self.get_default_config(config)
        self.lock = Lock()
        self.app = FastAPI()
        self.app.post('/loglikelihood')(self.serve_loglikelihood)
        self.app.post('/loglikelihood-rolling')(self.serve_loglikelihood_rolling)
        self.app.post('/generate')(self.serve_generate)
        self.app.post('/greedy-until')(self.serve_greedy_until)
        self.app.post('/chat')(self.serve_chat)
        self.app.get('/ready')(self.serve_ready)
        self.app = gr.mount_gradio_app(self.app, self.create_chat_app(), '/')

    @staticmethod
    def loglikelihood(prefix_text, text):
        raise NotImplementedError()

    @staticmethod
    def loglikelihood_rolling(text):
        raise NotImplementedError()

    @staticmethod
    def generate(text, temperature):
        raise NotImplementedError()

    @staticmethod
    def greedy_until(prefix_text, until, max_length):
        raise NotImplementedError()

    @staticmethod
    def to_list(x):
        if isinstance(x, np.ndarray):
            return x.tolist()
        return x

    def serve_ready(self):
        return 'Ready!\n'

    def serve_loglikelihood(self, data: InferenceRequest):
        with self.lock:
            if self.config.logging:
                absl.logging.info(
                    '\n========= Serving Log Likelihood Request ========= \n'
                    + pprint.pformat(data) + '\n'
                )

            if data.prefix_text is None:
                data.prefix_text = ['' for _ in data.text]

            prefix_text = [
                self.config.prepend_to_prefix + p + self.config.append_to_prefix
                for p in data.prefix_text
            ]
            text = [
                self.config.prepend_to_text + t + self.config.append_to_text
                for t in data.text
            ]

            log_likelihood = []
            is_greedy = []
            for i in trange(0, len(text), self.config.batch_size, ncols=0):
                batch_prefix_text = prefix_text[i:i + self.config.batch_size]
                batch_text = text[i:i + self.config.batch_size]
                batch_size = len(batch_text)

                if batch_size < self.config.batch_size:
                    extra = self.config.batch_size - batch_size
                    batch_prefix_text.extend(['a' for _ in range(extra)])
                    batch_text.extend(['a' for _ in range(extra)])

                batch_log_likelihood, batch_is_greedy = self.loglikelihood(
                    batch_prefix_text, batch_text
                )
                batch_log_likelihood = self.to_list(batch_log_likelihood)
                batch_is_greedy = self.to_list(batch_is_greedy)
                log_likelihood.extend(batch_log_likelihood[:batch_size])
                is_greedy.extend(batch_is_greedy[:batch_size])

            output = {
                'prefix_text': data.prefix_text,
                'text': data.text,
                'log_likelihood': log_likelihood,
                'is_greedy': is_greedy,
            }
            if self.config.logging:
                absl.logging.info(
                '\n========= Output ========= \n'
                + pprint.pformat(output) + '\n'
            )

        return output

    def serve_loglikelihood_rolling(self, data: InferenceRequest):
        with self.lock:
            if self.config.logging:
                absl.logging.info(
                    '\n========= Serving Log Likelihood Request ========= \n'
                    + pprint.pformat(data) + '\n'
                )

            text = [
                self.config.prepend_to_text + t + self.config.append_to_text
                for t in data.text
            ]
            log_likelihood = []
            is_greedy = []
            for i in trange(0, len(text), self.config.batch_size, ncols=0):
                batch_text = text[i:i + self.config.batch_size]
                batch_size = len(batch_text)

                if batch_size < self.config.batch_size:
                    extra = self.config.batch_size - batch_size
                    batch_text.extend(['a' for _ in range(extra)])

                batch_log_likelihood, batch_is_greedy = self.loglikelihood_rolling(
                    batch_text
                )
                batch_log_likelihood = self.to_list(batch_log_likelihood)
                batch_is_greedy = self.to_list(batch_is_greedy)
                log_likelihood.extend(batch_log_likelihood[:batch_size])
                is_greedy.extend(batch_is_greedy[:batch_size])

            output = {
                'text': data.text,
                'log_likelihood': log_likelihood,
                'is_greedy': is_greedy,
            }
            if self.config.logging:
                absl.logging.info(
                '\n========= Output ========= \n'
                + pprint.pformat(output) + '\n'
            )

        return output

    def serve_generate(self, data: InferenceRequest):
        with self.lock:
            if self.config.logging:
                absl.logging.info(
                    '\n========= Serving Generate Request ========= \n'
                    + pprint.pformat(data) + '\n'
                )
            prefix_text = [
                self.config.prepend_to_prefix + p + self.config.append_to_prefix
                for p in data.prefix_text
            ]

            if data.temperature is None:
                data.temperature = self.config.default_temperature

            output_text = []
            for i in trange(0, len(prefix_text), self.config.batch_size, ncols=0):
                batch_prefix_text = prefix_text[i:i + self.config.batch_size]
                batch_size = len(batch_prefix_text)

                if batch_size < self.config.batch_size:
                    extra = self.config.batch_size - batch_size
                    batch_prefix_text.extend(['a' for _ in range(extra)])

                batch_output_text = self.generate(
                    batch_prefix_text,
                    temperature=data.temperature,
                )
                output_text.extend(self.to_list(batch_output_text)[:batch_size])

            output = {
                'prefix_text': data.prefix_text,
                'output_text': output_text,
                'temperature': data.temperature,
            }
            if self.config.logging:
                absl.logging.info(
                    '\n========= Output ========= \n'
                    + pprint.pformat(output) + '\n'
                )
        return output

    def serve_greedy_until(self, data: InferenceRequest):
        with self.lock:
            if self.config.logging:
                absl.logging.info(
                    '\n========= Serving Greedy Until Request ========= \n'
                    + pprint.pformat(data) + '\n'
                )
            prefix_text = [
                self.config.prepend_to_prefix + p + self.config.append_to_prefix
                for p in data.prefix_text
            ]
            until = data.until
            max_length = self.config.greedy_until_max_length

            output_text = []
            for i in range(0, len(prefix_text), self.config.batch_size):
                batch_prefix_text = prefix_text[i:i + self.config.batch_size]
                batch_until = until[i:i + self.config.batch_size]
                batch_size = len(batch_prefix_text)

                batch_output_text = self.greedy_until(batch_prefix_text, batch_until, max_length)
                output_text.extend(self.to_list(batch_output_text)[:batch_size])

            output = {
                'prefix_text': data.prefix_text,
                'until': data.until,
                'max_length': max_length,
                'output_text': output_text,
            }
            if self.config.logging:
                absl.logging.info(
                    '\n========= Output ========= \n'
                    + pprint.pformat(output) + '\n'
                )
        return output

    def process_chat(self, prompt, context, temperature):
        context = (
            context + self.config.chat_user_prefix
            + prompt + self.config.chat_user_suffix
            + self.config.chat_lm_prefix
        )
        response = self.generate(
            [self.config.chat_prepend_text + context],
            temperature=float(temperature),
        )[0]
        context = context + response + self.config.chat_lm_suffix
        return response, context

    def serve_chat(self, data: ChatRequest):
        if data.temperature is None:
            data.temperature = self.config.default_temperature
        response, context = self.process_chat(
            data.prompt, data.context,
            temperature=data.temperature,
        )
        return {
            'response': response,
            'context': context,
            'temperature': data.temperature,
        }

    def create_chat_app(self):
        with gr.Blocks(analytics_enabled=False, title='EasyLM Chat') as gradio_chatbot:
            gr.Markdown('# Chatbot Powered by [EasyLM](https://github.com/young-geng/EasyLM)')
            gr.Markdown(self.config.notes)
            chatbot = gr.Chatbot(label='Chat history')
            msg = gr.Textbox(
                placeholder='Type your message here...',
                show_label=False
            )
            with gr.Row():
                send = gr.Button('Send')
                regenerate = gr.Button('Regenerate', interactive=False)
                clear = gr.Button('Reset')

            temp_slider = gr.Slider(
                label='Temperature', minimum=0, maximum=2.0,
                value=self.config.default_temperature
            )

            context_state = gr.State(['', ''])

            def user_fn(user_message, history, context):
                return {
                    msg: gr.update(value='', interactive=False),
                    clear: gr.update(interactive=False),
                    send: gr.update(interactive=False),
                    regenerate: gr.update(interactive=False),
                    chatbot: history + [[user_message, None]],
                    context_state: [context[1], context[1]],
                }

            def model_fn(history, context, temperature):
                history[-1][1], new_context = self.process_chat(
                    history[-1][0], context[0], temperature
                )
                return {
                    msg: gr.update(value='', interactive=True),
                    clear: gr.update(interactive=True),
                    send: gr.update(interactive=True),
                    chatbot: history,
                    context_state: [context[0], new_context],
                    regenerate: gr.update(interactive=True),
                }

            def regenerate_fn():
                return {
                    msg: gr.update(value='', interactive=False),
                    clear: gr.update(interactive=False),
                    send: gr.update(interactive=False),
                    regenerate: gr.update(interactive=False),
                }

            def clear_fn():
                return {
                    chatbot: None,
                    msg: '',
                    context_state: ['', ''],
                    regenerate: gr.update(interactive=False),
                }

            msg.submit(
                user_fn,
                inputs=[msg, chatbot, context_state],
                outputs=[msg, clear, send, chatbot, context_state, regenerate],
                queue=False
            ).then(
                model_fn,
                inputs=[chatbot, context_state, temp_slider],
                outputs=[msg, clear, send, chatbot, context_state, regenerate],
                queue=True
            )
            send.click(
                user_fn,
                inputs=[msg, chatbot, context_state],
                outputs=[msg, clear, send, chatbot, context_state, regenerate],
                queue=False
            ).then(
                model_fn,
                inputs=[chatbot, context_state, temp_slider],
                outputs=[msg, clear, send, chatbot, context_state, regenerate],
                queue=True
            )
            regenerate.click(
                regenerate_fn,
                inputs=None,
                outputs=[msg, clear, send, regenerate],
                queue=False
            ).then(
                model_fn,
                inputs=[chatbot, context_state, temp_slider],
                outputs=[msg, clear, send, chatbot, context_state, regenerate],
                queue=True
            )
            clear.click(
                clear_fn,
                inputs=None,
                outputs=[chatbot, msg, context_state, regenerate],
                queue=False
            )

        gradio_chatbot.queue(concurrency_count=1)
        return gradio_chatbot

    def run(self):
        if self.config.pre_compile != '':
            if self.config.pre_compile == 'all':
                pre_compile = ['loglikelihood', 'generate', 'greedy_until', 'chat']
            else:
                pre_compile = self.config.pre_compile.split(',')

            pre_compile_data = ['a' for _ in range(self.config.batch_size)]
            for task in pre_compile:
                if task == 'loglikelihood':
                    self.loglikelihood(pre_compile_data, pre_compile_data)
                    self.loglikelihood_rolling(pre_compile_data)
                elif task == 'generate':
                    self.generate(pre_compile_data, 1.0)
                elif task == 'greedy_until':
                    self.greedy_until(
                        pre_compile_data, pre_compile_data,
                        self.config.greedy_until_max_length
                    )
                elif task == 'chat':
                    self.process_chat('a', 'a', 1.0)
                else:
                    raise ValueError(f'Invalid precompile task: {task}!')

        uvicorn.run(self.app, host=self.config.host, port=self.config.port)


class LMClient(object):
    """ A simple client for the LM server. """

    @staticmethod
    def get_default_config(updates=None):
        config = ConfigDict()
        config.url = 'http://localhost:5007'
        config.batch_size = 1
        config.wait_for_ready = True
        config.dummy = False

        if updates is not None:
            config.update(ConfigDict(updates).copy_and_resolve_references())
        return config

    def __init__(self, config=None):
        self.config = self.get_default_config(config)
        if self.config.wait_for_ready:
            self.wait_for_ready()

    def wait_for_ready(self):
        if self.config.dummy:
            return
        while True:
            try:
                requests.get(urllib.parse.urljoin(self.config.url, 'ready'))
                return
            except (Timeout, ConnectionError) as e:
                time.sleep(10)

    @staticmethod
    def batched(iterator, batch_size):
        batch = []
        for example in iterator:
            batch.append(example)
            if len(batch) == batch_size:
                yield batch
                batch = []
        if len(batch) > 0:
            yield batch

    def loglikelihood(self, prefix, text):
        prefix, text = list(prefix), list(text)
        if self.config.dummy:
            return [-1.0 for _ in text], [False for _ in text]

        log_likelihood = []
        is_greedy = []

        batched_iterator = list(zip(
            self.batched(prefix, self.config.batch_size),
            self.batched(text, self.config.batch_size)
        ))
        for batch_prefix, batch_text in tqdm(batched_iterator, ncols=0):
            response = requests.post(
                urllib.parse.urljoin(self.config.url, 'loglikelihood'),
                json={'prefix_text': batch_prefix, 'text': batch_text}
            ).json()
            log_likelihood.extend(response['log_likelihood'])
            is_greedy.extend(response['is_greedy'])

        return log_likelihood, is_greedy

    def loglikelihood_rolling(self, text):
        text = list(text)
        if self.config.dummy:
            return [-1.0 for _ in text], [False for _ in text]

        log_likelihood = []
        is_greedy = []
        batched_iterator = list(self.batched(text, self.config.batch_size))
        for batch_text in tqdm(batched_iterator, ncols=0):
            response = requests.post(
                urllib.parse.urljoin(self.config.url, 'loglikelihood-rolling'),
                json={'text': batch_text}
            ).json()
            log_likelihood.extend(response['log_likelihood'])
            is_greedy.extend(response['is_greedy'])
        return log_likelihood, is_greedy

    def greedy_until(self, prefix, until):
        prefix, until = list(prefix), list(until)
        if self.config.dummy:
            results = []
            for u in until:
                if isinstance(u, str):
                    results.append('dummy text ' + u)
                else:
                    results.append('dummy text ' + u[0])
            return results

        batched_iterator = list(zip(
            self.batched(prefix, self.config.batch_size),
            self.batched(until, self.config.batch_size),
        ))
        output_text = []
        for batch_prefix, batch_until in tqdm(batched_iterator, ncols=0):
            response = requests.post(
                urllib.parse.urljoin(self.config.url, 'greedy-until'),
                json={'prefix_text': batch_prefix, 'until': batch_until}
            ).json()
            output_text.extend(response['output_text'])
        return output_text

    def generate(self, prefix, temperature=None):
        prefix = list(prefix)
        if self.config.dummy:
            return ['' for _ in prefix]

        output_text = []
        batched_iterator = list(self.batched(prefix, self.config.batch_size))
        for batch_prefix in tqdm(batched_iterator, ncols=0):
            response = requests.post(
                urllib.parse.urljoin(self.config.url, 'generate'),
                json={
                    'prefix_text': batch_prefix,
                    'temperature': temperature,
                }
            ).json()
            output_text.extend(response['output_text'])
        return output_text

    def chat(self, prompt, context, temperature=None):
        if self.config.dummy:
            return ''
        response = requests.post(
            urllib.parse.urljoin(self.config.url, 'chat'),
            json={
                'prompt': prompt,
                'context': context,
                'temperature': temperature,
            }
        ).json()
        return response['response'], response['context']