runner.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "log/slog"
  9. "math"
  10. "net"
  11. "net/http"
  12. "os"
  13. "path/filepath"
  14. "regexp"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/ollama/ollama/api"
  21. "github.com/ollama/ollama/llama"
  22. )
  23. type Sequence struct {
  24. // number of tokens evaluated
  25. nPast int
  26. // batch index
  27. iBatch int
  28. // number of tokens predicted so far
  29. numPredicted int
  30. // tokens left to evaluate
  31. tokens []int
  32. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  33. // TODO (jmorganca): simplify this
  34. pendingResponses []string
  35. // channel to send responses over
  36. responses chan string
  37. // channel to stop decoding (such as if the remote connection is closed)
  38. quit chan bool
  39. // number of tokens to predict
  40. numPredict int
  41. samplingCtx *llama.SamplingContext
  42. // channel to send back the embedding if embedding only
  43. embedding chan []float32
  44. // stop sequences
  45. stop []string
  46. // number of tokens to keep at the beginning when shifting context window
  47. numKeep int
  48. // true if an embedding are to be returned instead of text generation
  49. embeddingOnly bool
  50. doneReason string
  51. // Metrics
  52. startProcessingTime time.Time
  53. startGenerationTime time.Time
  54. numDecoded int
  55. numPromptTokens int
  56. }
  57. type NewSequenceParams struct {
  58. numPredict int
  59. stop []string
  60. numKeep int
  61. samplingParams *llama.SamplingParams
  62. embedding bool
  63. }
  64. func (s *Server) NewSequence(prompt string, params NewSequenceParams) *Sequence {
  65. tokens, err := s.lc.Model().Tokenize(prompt, true, true)
  66. if err != nil {
  67. panic(err)
  68. }
  69. if params.numKeep < 0 {
  70. params.numKeep = len(tokens)
  71. }
  72. if !params.embedding {
  73. // Subtracting 4 ensures that at least 1 token can be discarded during shift
  74. params.numKeep = min(params.numKeep, s.numCtx-4)
  75. params.numKeep += s.bosToken
  76. } else {
  77. // Embeddings are 1 shot - just truncate to the context window, without ever shifting
  78. params.numKeep = min(params.numKeep, s.numCtx)
  79. }
  80. // truncate to fit in context window
  81. if len(tokens) > s.numCtx {
  82. slog.Warn("truncating input prompt", "limit", s.numCtx, "prompt", len(tokens), "numKeep", params.numKeep)
  83. newTokens := tokens[:params.numKeep]
  84. newTokens = append(newTokens, tokens[len(tokens)-s.numCtx+params.numKeep:]...)
  85. tokens = newTokens
  86. }
  87. var sc *llama.SamplingContext
  88. if params.samplingParams != nil {
  89. sc = llama.NewSamplingContext(*params.samplingParams)
  90. for _, t := range tokens {
  91. sc.Accept(s.lc, t, false)
  92. }
  93. }
  94. return &Sequence{
  95. tokens: tokens,
  96. numPromptTokens: len(tokens),
  97. numPredict: params.numPredict,
  98. pendingResponses: make([]string, 0),
  99. responses: make(chan string, 1),
  100. quit: make(chan bool, 1),
  101. embedding: make(chan []float32, 1),
  102. samplingCtx: sc,
  103. embeddingOnly: params.embedding,
  104. stop: params.stop,
  105. numKeep: params.numKeep,
  106. }
  107. }
  108. type Server struct {
  109. model *llama.Model
  110. lc *llama.Context
  111. cc *llama.ClipContext
  112. batchSize int
  113. // parallel is the number of parallel requests to handle
  114. parallel int
  115. // seqs is the list of parallel sequences being evaluated
  116. // TODO (jmorganca): this can probably be moved into run()
  117. seqs []*Sequence
  118. // context window size
  119. numCtx int
  120. // does this model require a beginning of sequence token?
  121. bosToken int
  122. mu sync.Mutex
  123. cond *sync.Cond
  124. progress float32
  125. status string
  126. }
  127. func (s *Server) allNil() bool {
  128. for _, item := range s.seqs {
  129. if item != nil {
  130. return false
  131. }
  132. }
  133. return true
  134. }
  135. func (s *Server) shiftContext(seqIndex int) {
  136. seq := s.seqs[seqIndex]
  137. numLeft := seq.nPast - seq.numKeep
  138. numDiscard := numLeft / 2
  139. slog.Debug("context limit hit - shifting", "limit", s.numCtx, "nPast", seq.nPast,
  140. "numKeep", seq.numKeep, "numLeft", numLeft, "numDiscard", numDiscard)
  141. // TODO (jessegross): KV cache removal can fail for certain types of models
  142. // server.cpp doesn't handle this, though we can be more graceful
  143. s.lc.KvCacheSeqRm(seqIndex, seq.numKeep, seq.numKeep+numDiscard)
  144. s.lc.KvCacheSeqAdd(seqIndex, seq.numKeep+numDiscard, seq.nPast, -numDiscard)
  145. seq.nPast -= numDiscard
  146. }
  147. func incompleteUnicode(token string) bool {
  148. incomplete := false
  149. // check if there is incomplete UTF-8 character at the end
  150. for i := 1; i < 5 && i <= len(token); i++ {
  151. c := token[len(token)-i]
  152. if (c & 0xc0) == 0x80 {
  153. // continuation byte: 10xxxxxx
  154. continue
  155. }
  156. if (c & 0xe0) == 0xc0 {
  157. // 2-byte character: 110xxxxx ...
  158. incomplete = i < 2
  159. } else if (c & 0xf0) == 0xe0 {
  160. // 3-byte character: 1110xxxx ...
  161. incomplete = i < 3
  162. } else if (c & 0xf8) == 0xf0 {
  163. // 4-byte character: 11110xxx ...
  164. incomplete = i < 4
  165. }
  166. // else 1-byte character or invalid byte
  167. break
  168. }
  169. return incomplete
  170. }
  171. func (s *Server) removeSequence(seqIndex int, reason string) {
  172. seq := s.seqs[seqIndex]
  173. seq.doneReason = reason
  174. close(seq.responses)
  175. close(seq.embedding)
  176. seq.pendingResponses = []string{}
  177. seq.samplingCtx.Free()
  178. s.lc.KvCacheSeqRm(seqIndex, 0, -1)
  179. s.seqs[seqIndex] = nil
  180. }
  181. func (s *Server) run(ctx context.Context) {
  182. for {
  183. select {
  184. case <-ctx.Done():
  185. return
  186. default:
  187. s.processBatch()
  188. }
  189. }
  190. }
  191. func (s *Server) processBatch() {
  192. batch := llama.NewBatch(s.batchSize*len(s.seqs), 0, len(s.seqs))
  193. defer batch.Free()
  194. s.mu.Lock()
  195. for s.allNil() {
  196. s.cond.Wait() // Wait until an item is added
  197. }
  198. defer s.mu.Unlock()
  199. slog.Debug("Processing batch", "seqs", len(s.seqs))
  200. for i, seq := range s.seqs {
  201. if seq == nil {
  202. continue
  203. }
  204. // if past the num predict limit
  205. if seq.numPredict > 0 && seq.numPredicted > seq.numPredict {
  206. s.removeSequence(i, "limit")
  207. continue
  208. }
  209. if seq.nPast+len(seq.tokens) > s.numCtx {
  210. s.shiftContext(i)
  211. }
  212. if seq.startProcessingTime.IsZero() {
  213. seq.startProcessingTime = time.Now()
  214. }
  215. var numTokensProcessed int
  216. for j, t := range seq.tokens {
  217. // todo: make this n_batch
  218. if j >= s.batchSize {
  219. break
  220. }
  221. batch.Add(t, seq.nPast, []int{i}, numTokensProcessed+1 == len(seq.tokens))
  222. seq.nPast++
  223. numTokensProcessed++
  224. }
  225. seq.tokens = seq.tokens[numTokensProcessed:]
  226. seq.iBatch = batch.NumTokens() - 1
  227. }
  228. if batch.NumTokens() == 0 {
  229. return
  230. }
  231. err := s.lc.Decode(batch)
  232. if err != nil {
  233. slog.Error("failed to decode batch", "error", err)
  234. panic("Failed to decode")
  235. }
  236. for i, seq := range s.seqs {
  237. if seq == nil {
  238. continue
  239. }
  240. // don't sample prompt processing
  241. if len(seq.tokens) != 0 {
  242. continue
  243. }
  244. // if done processing the prompt, generate an embedding and return
  245. if seq.embeddingOnly {
  246. embd := s.lc.GetEmbeddingsSeq(i)
  247. if embd == nil {
  248. embd = s.lc.GetEmbeddingsIth(seq.iBatch)
  249. }
  250. seq.embedding <- embd
  251. s.removeSequence(i, "")
  252. continue
  253. }
  254. // sample a token
  255. token := seq.samplingCtx.Sample(s.lc, nil, seq.iBatch)
  256. seq.samplingCtx.Accept(s.lc, token, true)
  257. seq.numDecoded += 1
  258. if seq.numDecoded == 1 {
  259. seq.startGenerationTime = time.Now()
  260. }
  261. piece := s.model.TokenToPiece(token)
  262. seq.numPredicted++
  263. slog.Debug("sampled", "piece", piece)
  264. // if it's an end of sequence token, break
  265. if s.model.TokenIsEog(token) {
  266. // TODO (jmorganca): we should send this back
  267. // as it's important for the /api/generate context
  268. // seq.responses <- piece
  269. s.removeSequence(i, "stop")
  270. continue
  271. }
  272. seq.tokens = []int{token}
  273. seq.pendingResponses = append(seq.pendingResponses, piece)
  274. sequence := strings.Join(seq.pendingResponses, "")
  275. if incompleteUnicode(sequence) {
  276. continue
  277. }
  278. if ok, stop := findStop(sequence, seq.stop); ok {
  279. slog.Info("hit stop token", "stop", seq.stop)
  280. truncated := truncateStop(seq.pendingResponses, stop)
  281. for _, p := range truncated {
  282. select {
  283. case seq.responses <- p:
  284. case <-seq.quit:
  285. break
  286. }
  287. }
  288. s.removeSequence(i, "stop")
  289. continue
  290. }
  291. if containsStopSuffix(sequence, seq.stop) {
  292. continue
  293. }
  294. for _, p := range seq.pendingResponses {
  295. select {
  296. case seq.responses <- p:
  297. case <-seq.quit:
  298. s.removeSequence(i, "connection")
  299. break
  300. }
  301. }
  302. seq.pendingResponses = []string{}
  303. }
  304. }
  305. type Options struct {
  306. api.Runner
  307. NumKeep int `json:"n_keep"`
  308. Seed int `json:"seed"`
  309. NumPredict int `json:"n_predict"`
  310. TopK int `json:"top_k"`
  311. TopP float32 `json:"top_p"`
  312. MinP float32 `json:"min_p"`
  313. TFSZ float32 `json:"tfs_z"`
  314. TypicalP float32 `json:"typical_p"`
  315. RepeatLastN int `json:"repeat_last_n"`
  316. Temperature float32 `json:"temperature"`
  317. RepeatPenalty float32 `json:"repeat_penalty"`
  318. PresencePenalty float32 `json:"presence_penalty"`
  319. FrequencyPenalty float32 `json:"frequency_penalty"`
  320. Mirostat int `json:"mirostat"`
  321. MirostatTau float32 `json:"mirostat_tau"`
  322. MirostatEta float32 `json:"mirostat_eta"`
  323. PenalizeNewline bool `json:"penalize_nl"`
  324. Stop []string `json:"stop"`
  325. }
  326. type CompletionRequest struct {
  327. Prompt string `json:"prompt"`
  328. Images []string `json:"images"`
  329. Grammar string `json:"grammar"`
  330. Options
  331. }
  332. type Timings struct {
  333. PredictedN int `json:"predicted_n"`
  334. PredictedMS float64 `json:"predicted_ms"`
  335. PromptN int `json:"prompt_n"`
  336. PromptMS float64 `json:"prompt_ms"`
  337. }
  338. type CompletionResponse struct {
  339. Content string `json:"content"`
  340. Stop bool `json:"stop"`
  341. Model string `json:"model,omitempty"`
  342. Prompt string `json:"prompt,omitempty"`
  343. StoppedLimit bool `json:"stopped_limit,omitempty"`
  344. PredictedN int `json:"predicted_n,omitempty"`
  345. PredictedMS float64 `json:"predicted_ms,omitempty"`
  346. PromptN int `json:"prompt_n,omitempty"`
  347. PromptMS float64 `json:"prompt_ms,omitempty"`
  348. Timings Timings `json:"timings"`
  349. }
  350. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  351. var req CompletionRequest
  352. req.Options = Options(api.DefaultOptions())
  353. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  354. http.Error(w, "Bad request", http.StatusBadRequest)
  355. return
  356. }
  357. // Set the headers to indicate streaming
  358. w.Header().Set("Content-Type", "application/json")
  359. w.Header().Set("Transfer-Encoding", "chunked")
  360. w.WriteHeader(http.StatusOK)
  361. var samplingParams llama.SamplingParams
  362. samplingParams.TopK = req.TopK
  363. samplingParams.TopP = req.TopP
  364. samplingParams.MinP = req.MinP
  365. samplingParams.TfsZ = req.TFSZ
  366. samplingParams.TypicalP = req.TypicalP
  367. samplingParams.Temp = req.Temperature
  368. samplingParams.RepeatLastN = req.RepeatLastN
  369. samplingParams.PenaltyRepeat = req.RepeatPenalty
  370. samplingParams.PenaltyFreq = req.FrequencyPenalty
  371. samplingParams.PenaltyPresent = req.PresencePenalty
  372. samplingParams.Mirostat = req.Mirostat
  373. samplingParams.MirostatTau = req.MirostatTau
  374. samplingParams.MirostatEta = req.MirostatEta
  375. samplingParams.PenalizeNl = req.PenalizeNewline
  376. samplingParams.Seed = uint32(req.Seed)
  377. samplingParams.Grammar = req.Grammar
  378. seq := s.NewSequence(req.Prompt, NewSequenceParams{
  379. numPredict: req.NumPredict,
  380. stop: req.Stop,
  381. numKeep: req.NumKeep,
  382. samplingParams: &samplingParams,
  383. embedding: false,
  384. })
  385. // TODO (jmorganca): add to sequence queue instead of
  386. // failing if a slot isn't available
  387. s.mu.Lock()
  388. for i, sq := range s.seqs {
  389. if sq == nil {
  390. s.seqs[i] = seq
  391. s.cond.Signal()
  392. break
  393. }
  394. }
  395. s.mu.Unlock()
  396. // stream the response
  397. for content := range seq.responses {
  398. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  399. Content: content,
  400. }); err != nil {
  401. log.Println("Failed to encode result:", err)
  402. close(seq.quit)
  403. return
  404. }
  405. flusher, ok := w.(http.Flusher)
  406. if !ok {
  407. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  408. close(seq.quit)
  409. return
  410. }
  411. flusher.Flush()
  412. }
  413. // Send the stop
  414. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  415. Stop: true,
  416. Timings: Timings{
  417. PromptN: seq.numPromptTokens,
  418. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  419. PredictedN: seq.numDecoded,
  420. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  421. },
  422. }); err != nil {
  423. log.Println("Failed to encode result:", err)
  424. return
  425. }
  426. flusher, ok := w.(http.Flusher)
  427. if !ok {
  428. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  429. return
  430. }
  431. flusher.Flush()
  432. }
  433. type EmbeddingRequest struct {
  434. Content string `json:"content"`
  435. }
  436. type EmbeddingResponse struct {
  437. Embedding []float32 `json:"embedding"`
  438. }
  439. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  440. var req EmbeddingRequest
  441. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  442. http.Error(w, "Bad request", http.StatusBadRequest)
  443. return
  444. }
  445. w.Header().Set("Content-Type", "application/json")
  446. slog.Debug("embedding request", "content", req.Content)
  447. seq := s.NewSequence(req.Content, NewSequenceParams{embedding: true})
  448. // TODO (jessegross): Wait for a free slot instead of failing and blocking forever
  449. s.mu.Lock()
  450. for i, sq := range s.seqs {
  451. if sq == nil {
  452. s.seqs[i] = seq
  453. s.cond.Signal()
  454. break
  455. }
  456. }
  457. s.mu.Unlock()
  458. embedding := <-seq.embedding
  459. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  460. Embedding: embedding,
  461. }); err != nil {
  462. log.Println("Failed to encode result:", err)
  463. return
  464. }
  465. }
  466. type HealthResponse struct {
  467. Status string `json:"status"`
  468. Progress float32 `json:"progress"`
  469. }
  470. // TODO (jmorganca): is it safe to do this concurrently with updating status?
  471. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  472. w.Header().Set("Content-Type", "application/json")
  473. if err := json.NewEncoder(w).Encode(&HealthResponse{
  474. Status: s.status,
  475. Progress: s.progress,
  476. }); err != nil {
  477. log.Println("Failed to encode result:", err)
  478. return
  479. }
  480. }
  481. func main() {
  482. mpath := flag.String("model", "", "Path to model binary file")
  483. ppath := flag.String("mmproj", "", "Path to projector binary file")
  484. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  485. batchSize := flag.Int("batch-size", 512, "Batch size")
  486. nGpuLayers := flag.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  487. mainGpu := flag.Int("main-gpu", 0, "Main GPU")
  488. flashAttention := flag.Bool("flash-attn", false, "Enable flash attention")
  489. kvSize := flag.Int("ctx-size", 2048, "Context (or KV cache) size")
  490. lpath := flag.String("lora", "", "Path to lora layer file")
  491. port := flag.Int("port", 8080, "Port to expose the server on")
  492. threads := flag.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  493. verbose := flag.Bool("verbose", false, "verbose output (default: disabled)")
  494. noMmap := flag.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  495. mlock := flag.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  496. tensorSplit := flag.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  497. // These are either ignored by llama.cpp or have no significance to us
  498. _ = flag.Bool("embedding", false, "enable embedding vector output (default: disabled)")
  499. _ = flag.Bool("log-disable", false, "disables logging to a file")
  500. _ = flag.Bool("memory-f32", false, "use f32 instead of f16 for memory key+value (default: disabled) not recommended: doubles context memory required and no measurable increase in quality")
  501. flag.Parse()
  502. level := slog.LevelInfo
  503. if *verbose {
  504. level = slog.LevelDebug
  505. }
  506. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  507. Level: level,
  508. AddSource: true,
  509. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  510. if attr.Key == slog.SourceKey {
  511. source := attr.Value.Any().(*slog.Source)
  512. source.File = filepath.Base(source.File)
  513. }
  514. return attr
  515. },
  516. })
  517. slog.SetDefault(slog.New(handler))
  518. server := &Server{
  519. numCtx: *kvSize / *parallel,
  520. batchSize: *batchSize,
  521. parallel: *parallel,
  522. seqs: make([]*Sequence, *parallel),
  523. status: "loading model",
  524. }
  525. // TODO (jessegross): This should be in a separate goroutine so we can report progress,
  526. // otherwise Ollama can timeout for large model loads
  527. // load the model
  528. llama.BackendInit()
  529. var tensorSplitFloats []float32
  530. if *tensorSplit != "" {
  531. stringFloats := regexp.MustCompile(",").Split(*tensorSplit, -1)
  532. tensorSplitFloats = make([]float32, 0, len(stringFloats))
  533. for _, s := range stringFloats {
  534. f, _ := strconv.ParseFloat(s, 32)
  535. tensorSplitFloats = append(tensorSplitFloats, float32(f))
  536. }
  537. }
  538. params := llama.ModelParams{
  539. NumGpuLayers: *nGpuLayers,
  540. MainGpu: *mainGpu,
  541. UseMmap: !*noMmap && *lpath == "",
  542. UseMlock: *mlock,
  543. TensorSplit: tensorSplitFloats,
  544. Progress: func(progress float32) {
  545. slog.Debug("Loading model", "progress %", math.Round(float64(progress*100)))
  546. server.progress = progress
  547. },
  548. }
  549. server.model = llama.LoadModelFromFile(*mpath, params)
  550. if *lpath != "" {
  551. err := server.model.ApplyLoraFromFile(*lpath, 1.0, "", *threads)
  552. if err != nil {
  553. panic(err)
  554. }
  555. }
  556. ctxParams := llama.NewContextParams(*kvSize, *threads, *flashAttention)
  557. server.lc = llama.NewContextWithModel(server.model, ctxParams)
  558. if server.model.ShouldAddBOSToken() {
  559. server.bosToken = 1
  560. }
  561. if *ppath != "" {
  562. server.cc = llama.NewClipContext(*ppath)
  563. }
  564. server.cond = sync.NewCond(&server.mu)
  565. ctx, cancel := context.WithCancel(context.Background())
  566. go server.run(ctx)
  567. addr := "127.0.0.1:" + strconv.Itoa(*port)
  568. listener, err := net.Listen("tcp", addr)
  569. if err != nil {
  570. fmt.Println("Listen error:", err)
  571. return
  572. }
  573. defer listener.Close()
  574. mux := http.NewServeMux()
  575. mux.HandleFunc("/embedding", server.embeddings)
  576. mux.HandleFunc("/completion", server.completion)
  577. mux.HandleFunc("/health", server.health)
  578. httpServer := http.Server{
  579. Handler: mux,
  580. }
  581. server.status = "ok"
  582. log.Println("Server listening on", addr)
  583. if err := httpServer.Serve(listener); err != nil {
  584. log.Fatal("server error:", err)
  585. }
  586. cancel()
  587. }